上一篇文章咱们讲到了如何打造本身的Javascript类库 接下来咱们发现使用外部资源引用方式后,修复一些bug和新增一些功能必需要等到下一版本发布,在项目中才能使用,并且修改类库后本地运行的代码没法即时刷新,影响咱们的开发效率,因而咱们又想在开发时把咱们的外部资源引用方式切换回模块引用。html
package.jsonnode
"start": "webpack-dev-server --mode=development --open",
"start:module": "webpack-dev-server --mode=development --open --externals=false"
复制代码
start
:外部资源引用模式。 start:module
:模块引用模式。当咱们须要切换回模块引用方式时,运行这个命令启动程序。react
webpack.config.jswebpack
const HtmlWebpackPlugin = require('html-webpack-plugin');
const args = require('node-args');
const isExternals = args.externals !== false;
module.exports = {
//...
plugins: [
//...
new HtmlWebpackPlugin({
filename: 'index.html',
template: `${__dirname}/src/template.ejs`,
//...
// 添加参数IS_EXTERNALS,后面母版页会使用
IS_EXTERNALS: isExternals,
}),
],
// 若是非外部资源引用方式,设置externals为undefined
externals: isExternals ? {
//...
'my-library': 'myLibrary'
} : undefined,
};
复制代码
template.ejs 母版页web
<% if (htmlWebpackPlugin.options.IS_EXTERNALS) { %>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0/umd/react.production.min.js"></script>
//...
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/my-library/13.0.0/my-library.min.js"></script>
<% } %>
复制代码
根据上面传入的IS_EXTERNALS参数,设置是否须要引用外部资源ajax
至此,咱们完成了切换外部资源和模块引用两种使用方式。json