webpack noParse参数

webpack noParse

webpack精准过滤不需要解析的文件

webpack配置中 module配置下有一条配置项叫noParse

{
    module:{
        noParse: /jquery|lodash/,  //接收参数  正则表达式 或函数
        noParse:function(contentPath){
            return /jquery|lodash/.test(contentPath);
        }
    }
}

主要用到的是函数部分

function (contentPath){
//contentPath 是一个复合的路径 ,基于webpack3测试
//包含loader路径以及资源路径,而我们需要过滤的仅仅是资源路径
//contentPath结构 loader1!loader2!..loaderx!assetsPath
}

假如一个css资源index.css,loader配置如下

use:[{
     loader: 'style-loader' //生成的css插入到html
}, {
    loader: 'css-loader' //使js中能加载css     
}]

那么contentPath会如下

contentPath = E:/project/node_modules/css-loader/index.js!E:/project/node_modules/style-loader/index.js!E:/project/src/index.css!

但是我们只需要过滤资源路径

完整代码如下:

      noParse: function(contentPath) {
            //contentPath   构成   loader1Path!loader2Path!assetsPath  
            //我们只需要过滤webpack解析资源的路径   而不需要过滤loader的路径
            contentPath = contentPath.split("!").pop();
            
            let shouldNotParse = false,
                 filename = contentPath.split("\\").pop(),
                 prefixPath = contentPath.split("\\"),
                 noParseFolders = [/static/, /node_modules/], //不需要解析的文件夹名称的正则表达式
                 noParseFiles = [/jquery/]; //不需要解析的文件名称

            shouldNotParse = prefixPath.find(curPath => {
                return noParseFolders.find(folderExp => folderExp.test(curPath));
            });

            !shouldNotParse && (shouldNotParse = noParseFiles.find(exp => exp.test(filename)));

            return !!shouldNotParse;
 }

猜你喜欢

转载自blog.csdn.net/qq_33207773/article/details/88635573