Implementation method of WebPack dynamic bulk loading file

Recently, the author encountered a small demand in the work:

To achieve a component to play the frame picture

This demand itself is not complicated, but it is necessary to introduce ten pictures in the component, just like this:

// is such a way, subscript 0 Start ~ import frame0 from ‘./assets/frame_0.png’import frame1 from’ ./assets/frame_1.png’Import frame2 from ‘./assets/frame_2.png’// .. 省 N 张 张 i i77 from’ ./assets/frame_8.png’Import frame8 from ‘./assets/frame_9.png’Import frame9 from’ ./assets/frame_10.png’

 as a The programmer of code cleansing, I don't allow this repeating code to exist, so I don't have any simple way.  
Method 1: Bypass Webpack

Since the author is Vue-CLI 3, familiar small partners know that the image is fixed in a fixed format Put it under the public folder and then introduced directly in the code in the code. If you do this, you can construct a URL array according to the file name. Simple code is as follows: const frames = [] _. Times (10, v => {frames. Push (`/ images / frame _ $ {v} .png`)} // Then you get 10 URLs’ arrays.

This method is in itself a expedients vue-cli provided, it has several disadvantages:
  can not use webpack processing resources, not generating a content hash is not conducive to cache updates  
using the url-loader can not be linked into the base64 string to reduce network resource request

method II: require
  • is due to the import static keyword, so if you want to bulk load files, you can use require, but directly like this is not enough to write the following:

const frames = [] _. times (10, v => {const path = `./assets/images/frame _ $ {v} .png` frames.push (require (path))}

the above code is to determine the path of the program is running, i.e. belongs runtime phase, and require webpack the file location is determined in a construction phase, it can not webpack . presumed where the path in the
 but it can be written:   
const frames = [] _ ​​times (10, v => {frames. .push (require ( `./assets/images/frame _ $ {v} .png`))} // frames is obtained in the tape path hash value

Although both versions no difference in syntax, but the second wording suggests webpack when building, webPack will add all the files in ./assets/Images to the bundle, so you can find the corresponding file at your runtime.
 When using methods, the author tries to extract the logic loaded to other modules to other modules:   
Export function loadAll (N, prefix , suffix {const frames = [] _.Times (n, v => {frames.push (Require (‘./’ + prefix + v + suffix)})})})})})})})})})})})} Return frames}

But obviously failed, because the extracted code, the running context belongs to another module, so it will not be able to find files in the relative path.
 Method 3: Require.Context   
The above two methods are not very elegant, so I will go to the Webpack document, finally, let me find Such a method: Require.context

Require.context (Directory: String, IncludeSubdirs: boolean / * Optional, default is true * /, filter: regexp / * Optional, the default is /^\.\/.* or: string / * Optional, ‘Sync’ | ‘Eager’ | ‘Weak’ | ‘Lazy’ | ‘lazy-overce’, the default value is ‘sync’ * /)

Specifies a series of complete dependencies, through a Directory path, one INCludesubdirs options, a Filter finer granular control module introduction and a MODE definition loading method. The module can then be easily parsed.

We still look at the example:

Const frames = [] const context = required.context (‘./assets/Images’, false, /frame_\d +.png/)context.keys().ForeAach (K => {frames.push (context (k))})
The code here created a Require context through Require.Context.

The first parameter specifies the folder that needs to be loaded, which is the current directory of the component ./assets/images folder

The second parameter specifies whether the subdirectory needs to be included. Since there is no subdirectory, the third parameter specifies the matching rules that need to be included, we use a regular representation

and then use context.keys () Can get the file path list of this context, and the context itself is also a method, which is equivalent to the context-based request, we put the request after the request in the array, in fact, the path in the array is actually with a Hash value, as I am Image of the project:
  ["/ static / img / frame_0.965ef86f.png", "/static/img/frame_1.c7465967.png", "/ Static /IMG/FRAME_2.41E82904.png "" / static / img / frame_3.Faef7de9.png "," /static/img/frame_4.27ebbe45.png "," /static/img/frame_5.d98cbebe.png "," /static/img/frame_6.c10859bc.png "," / Static / IMG / frame_7.5e9cbdf0.png "," /static/img/frame_8.b3b92c71.png "," /static/img/frame_9.36660295.png"]

And if the inline picture is set, there may be a base64 string of pictures in the array.

  • Refact
  • method three has solved our Question, and can batch files in a folder in the Require. But the logic of Foreach is obviously repetitive, so we certainly extract it. You only need to introduce when multiple components are called:
Public Module:

/ ** * Batch Load Frame Image * @Param {Function} Context – Require.Context created function * @returns {array
} Return all images * / function loadFrames (context) {const frames = [] context.keys (). Foreach (k => {frames.push (CONTEXT (k))}) Return frames}

const context = request.contexT (‘./ asseserts / images’, false, /frame_\d +.png/)const frames = loadingframes (context)

Dachel is good! Interested partners can click on the document link to view detailed documentation ~

Reference link

Require.context WebPack Dynamic Require
   This article on the implementation method of WebPack dynamic bulk file is introduced to this, more related WebPack dynamic bulk loading file content, please search for Tumi cloud previous articles or continue to browse the following related articles, I hope everyone will support Tumi cloud!  
© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment