Preface
I often encounter such a problem. When preloading the image resources of h5 project, we often need to manually get one image address and store it in the array, and then pre load the traversal, such as this:
let imgList = ['http://domain.com/img/1.jpg','http://domain.com/img/2.jpg','http://domain.com/img/3.jpg',...];
In the spirit of being lazy, we can write a webpack loader to handle it, and then return such an array to us.
It is expected to call this way on the page to get the picture of img folder under the project directory and return an array of URL s.
let imgList = __getPath('img');
principle
The amount of code is very small, but the principle is also relatively simple. Use regular matching \\\\\\\\\\\
[require("img/1.jpg"),require("img/2.jpg"),require("img/3.jpg"),...]
Finally, the content of return will be executed, and then the URL array of the image will be returned.
const fs = require("fs") const path = require('path'); const glob = require('glob'); module.exports = function (content) { let fileReg = /__getPath\(([^\)]+)\)/gim; let rootPath = path.join(this.options.context, "/src"); //src path under Project let filepath = this.context;//Directory where the current processing file is located //console.log(this.options.context) //console.log(filepath) content = content.replace(fileReg, (ret, src) => { let pathName = src.replace(/'|"/g, ""); let resList = glob.sync(path.join(rootPath, pathName) + "/*"); let result = '['; for (let i = 0; i < resList.length; i++) { let respath = path.relative(filepath, resList[i]).replace(/\\/g, "/") //Picture relative path result += "require('" + respath + "')" + "," } result = result.substr(0,result.length-1) + "]"; return result; }) return content; }
Installation and use
I named it imgurl loader and published it to npm.
npm install --save-dev imgurl-loader
Source code: https://github.com/xiaojiecong/imgurl-loader
Demo: https://github.com/xiaojiecong/imgurl-loader-demo
(if you can help us, you can star o  ̄) o)