Write a web pack loader to get the pictures under the specified directory and return the picture URL array


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');


The amount of code is very small, but the principle is also relatively simple. Use regular matching \\\\\\\\\\\


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
    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)

Keywords: node.js github npm Webpack

Added by JakeTheSnake3.0 on Tue, 05 Nov 2019 17:25:23 +0200