使用 vue-part-compile-loader 加速构建

217 阅读1分钟

加速 nuxt项目构建速度,实现按需编译,秒级热更新。项目越大,效果越明显

  1. 方案原理: 利用路由匹配,对不需要进行渲染的路由组件拦截,使用 vue-part-compile-loader.vue 文件进行匹配 (本质上就是按需编译,按照开发时需要用到的页面进行编译)

  2. 核心利用 webpack loaderrunnerpitch 进行熔断,实现按需编译

  3. 只可用于开发环境,其他环境禁止使用

如何使用:
  1. 在 client/config 目录下 新建一个 fastLoaderConfig.js, 里面维护 vue-part-compile-loader 配置
  2. 各开发者按照自己需要维护的页面进行修改 exclude
  3. 会把 client/config/fastLoaderConfig.js 添加到 .gitignore 文件中,方便 fastLoaderConfig.js 文件可以千人千面进行配置 (每个同学需要更改的页面不一致,因此需要按需编译的文件路径也不一样,此文件不需要提交)
  4. npm i vue-part-compile-loader -D
// client/config/fastLoaderConfig.js

module.exports = (module) => {
    module.rules = [
        ...module.rules,
        {
            // 匹配到这些 .vue 文件走 vue-part-compile-loader
            test: /pages/_lang/[\s\S]*.vue$/,
            exclude: /pages/_lang/(login|markets)(/[\s\S]*)?.vue$/,
            use: ['vue-part-compile-loader']
        }
    ]
}
// nuxt.config.js

const fastLoaderConfigPath = './client/config/fastLoaderConfig.js';
const isFileExits = fs.existsSync(fastLoaderConfigPath)
const fastLoaderConfig = isFileExits ? require(fastLoaderConfigPath) : () => {}

module.exports = {
   ..., 
   
   extend(config, { isClient, loaders: { vue } }) {
       ...
       if(process.env._ENV === 'dev'){
         fastLoaderConfig(config.module)
       },
       ...
   },
   ...,
}
// .gitignore

...
client/config/fastLoaderConfig.js
效果如下:
  1. 未使用 vue-part-compile-loader

    1. 启动: 大概 90s 左右 (不同型号电脑速度不一样,这里测试是 M2)
    2. 热更新: 大概 3s 左右 (不同型号电脑速度不一样,这里测试是 M2)
  2. 启用 vue-part-compile-loader 之后

    1. 启动: 大概 22s 左右 (不同型号电脑速度不一样,这里测试是 M2)
    2. 热更新: 大概 1.5s 左右 (不同型号电脑速度不一样,这里测试是 M2)