webpack--指定文件跳过编译

673 阅读2分钟

大家好,我苏先生,一名热爱钻研、乐于分享的前端工程师,我正在进行vue3源码和TypeScript的专栏更新,感兴趣的小伙伴跟着我一起卷死同行吧🧐

github与好文

背景

开发迭代中,由于需求的变化,会存在部分模块后续不再使用的情况,一般都只是从菜单权限上进行禁用,而对于源代码,不会直接进行删除,因此就需要一种机制能够排除掉暂时不用的模块从而提高打包效率

文章只大致写下思路,具体可以看github源码,然后,如果觉得对您有用,希望能得到您的star

思路

  • 通过对指定的模块进行判定,在匹配时进行过滤,这通过beforeResolve可以很容易的做到

  • 开发中往往会相互引用模块,所以直接一刀切肯定不行,因此还需要去分析其引用关系,这可以在buildStart中实现

安装与使用

  • 安装
yarn add webpack-skip-compile
const SkipCompile = require("webpack-skip-compile")
new SkipCompile('src/pages',[
    'dataCenter'
],{
    alias:[{
        key:'@',
        value:resolve('src')
      }],
    include:['.vue']
})

效果对比

  • 使用插件前

image.png

  • 使用插件后

image.png

实现

  • buildStart

在服务的启动阶段,我们依次读取文件,并解析其import引入

for (let i = 0; i < files.length; i++) {
      const file = files[i];
      if (fs.existsSync(file)) {
        const code = fs.readFileSync(file, "utf-8");
        const jsCode = getCode(strip(code));
        if (jsCode.trim()) {
          // fs.writeFileSync(tPath, jsCode);
          const imps = parseImports(jsCode);
          
        }
    }
}

然后去判断当前文件中是否引入了被跳过编译的文件

const igIndex = igs.findIndex((ig) => actualImp.includes(ig) );

只有自身未被设置跳过编译,并且引用了被跳过编译的文件时,向用户输出提示,并不再接管编译操作

if (igIndex > -1) {
   const isIg =  igs.find(i=>file.includes(i))
   if(isIg) continue
   console.warn(
         `文件(${file})中的(${imp})与配置的文件(${this.igs[igIndex]})存在引用关系,请检查`
    );
   global.conflict = true;
   break;
}

  • beforeResolve

只有通过引用关系检查后,才允许做跳过处理

const { context = "", request = "" } = payload || {};
if (request.includes("node_modules")) return payload;
const igs = global.igs
const absolutePath = path.resolve(context, request);
if (igs.find(v=>absolutePath.includes(v))) {
   return null
}
return payload;