1、在页面中加入需要引入的lib地址,如下:
<head> <script src="//cdn.bootcss.com/jquery.min.js"></script> <script src="//cdn.bootcss.com/underscore.min.js"></script> <script src="/static/common/react.min.js"></script> <script src="/static/common/react-dom.js"></script> <script src="/static/common/react-router.js"></script> <script src="/static/common/immutable.js"></script> </head>
2、在webapck.config.js中加入external配置项:
module.export = {
externals: {
'react-router': {
amd: 'react-router',
root: 'ReactRouter',
commonjs: 'react-router',
commonjs2: 'react-router'
},
react: {
amd: 'react',
root: 'React',
commonjs: 'react',
commonjs2: 'react'
},
'react-dom': {
amd: 'react-dom',
root: 'ReactDOM',
commonjs: 'react-dom',
commonjs2: 'react-dom'
}
}
}
这里要提到的一个细节是:此类文件在配置前,构建这些资源包时需要采用amd/commonjs/cmd相关的模块化进行兼容封装,即打包好的库已经是umd模式包装过的,如在node_modules/react-router中我们可以看到umd/ReactRouter.js之类的文件,只有这样webpack中的require和import * from 'xxxx'才能正确读到该类包的引用,在这类js的头部一般也能看到如下字样:
if (typeof exports === 'object' && typeof module === 'object') {
module.exports = factory(require("react"));
} else if (typeof define === 'function' && define.amd) {
define(["react"], factory);
} else if (typeof exports === 'object') {
exports["ReactRouter"] = factory(require("react"));
} else {
root["ReactRouter"] = factory(root["React"]);
}
3、非常重要的是一定要在output选项中加入如下一句话:
output: {
libraryTarget: 'umd'
}
由于通过external提取过的js模块是不会被记录到webapck的chunk信息中,通过libraryTarget可告知我们构建出来的业务模块,当读到了externals中的key时,需要以umd的方式去获取资源名,否则会有出现找不到module的情况。
通过配置后,我们可以看到对应的资源信息已经可以在浏览器的source map中读到了。

对应的资源也可以直接由页面外链载入,有效地减小了资源包的体积。

方案三、利用 DllPlugin 和 DllReferencePlugin 预编译资源模块
我们的项目依赖中通常会引用大量的npm包,而这些包在正常的开发过程中并不会进行修改,但是在每一次构建过程中却需要反复的将其解析,如何来规避此类损耗呢?这两个插件就是干这个用的。
