记载: CND 做缓存,前端工程化方面如何处理?

236 阅读1分钟

同步chunk类型

  1. 首先,htmlWebpackPlugin设为chunk不自动注入,
{
    plugins: [
        new HtmlWebpackPlugin({
        filename: 'index.jsp',
        inject: false, // 这是重点
        template: 'src/index/index.jade',
        favicon: 'src/shared/assets/images/active-favicon.ico',
      })
    ]
}
  1. 其次,利用template模块中,通过htmlWebpackPlugin.files.js来获取我们生成的chunk文件名称,重新拼接为CDN上的地址获取。
each val, index in htmlWebpackPlugin.files.js
      script(src!=akamaiUrl + val)

异步chunk类型

  1. 存在require.ensure() 或者 import() 动态异步加载的chunk, 第一步使用webpack-require-from的plugin, 利用 WebpackRequireFrom 来指定加载方法
// js中若存在异步懒加载的内容
require.ensure([], ()=>require('intl'), 'intl-polyfill');
or
import(/* webpackChunkName: "intl-polyfill" */ 'intl').then(()=> console.log('intl async loaded.'))


// webpack配置
{
    plugins: [
        new WebpackRequireFrom({ replaceSrcMethodName: '__WEBPACK_ASSETS_PATH__' }),
    ]
}
  1. 第二步,在template中定义指定的方法,来获取异步加载的资源路径,然后对其重写,拼接为CDN上的地址。
// eg:jade文件
script.
        window.__WEBPACK_ASSETS_PATH__ = function(path) {
          var regexp = /\/js\/chunk\.intl-polyfill/;
          if (path.match(regexp)) {
            return path.replace(regexp, "!{baseUrl}" + '/js/chunk.intl-polyfill');
          }
          return path;
        };