同步chunk类型
- 首先,htmlWebpackPlugin设为chunk不自动注入,
{
plugins: [
new HtmlWebpackPlugin({
filename: 'index.jsp',
inject: false,
template: 'src/index/index.jade',
favicon: 'src/shared/assets/images/active-favicon.ico',
})
]
}
- 其次,利用template模块中,通过htmlWebpackPlugin.files.js来获取我们生成的chunk文件名称,重新拼接为CDN上的地址获取。
each val, index in htmlWebpackPlugin.files.js
script(src!=akamaiUrl + val)
异步chunk类型
- 存在require.ensure() 或者 import() 动态异步加载的chunk, 第一步使用webpack-require-from的plugin, 利用
WebpackRequireFrom 来指定加载方法
require.ensure([], ()=>require('intl'), 'intl-polyfill');
or
import( 'intl').then(()=> console.log('intl async loaded.'))
{
plugins: [
new WebpackRequireFrom({ replaceSrcMethodName: '__WEBPACK_ASSETS_PATH__' }),
]
}
- 第二步,在template中定义指定的方法,来获取异步加载的资源路径,然后对其重写,拼接为CDN上的地址。
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;
};