Webpack学习笔记(四):管理输出
目的
避免在index.html中手动引入所有资源,使用插件进行管理,而不是继续手动管理
分离入口
代码继承自Webpack学习笔记(三):管理资源
1.项目中添加新的js文件,作为打包的入口
webpack-demo
|- package.json
|- webpack.config.js
|- /dist
|- /src
|- index.js
+ |- print.js
|- /node_modules
2.修改webpack.config.js,将打包入口分离
const path = require('path');
module.exports = {
- entry: './src/index.js',
+ entry: {
+ app: './src/index.js',
+ print: './src/print.js'
+ },
output: {
- filename: 'bundle.js',
+ filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
3.修改index.html,为 webpack 分离入口做好准备
<!doctype html>
<html>
<head>
- <title>管理资源</title>
+ <title>管理输出</title>
+ <script src="./print.bundle.js"></script>
</head>
<body>
- <script src="./bundle.js"></script>
+ <script src="./app.bundle.js"></script>
</body>
</html>
设置 HtmlWebpackPlugin
上面的代码中存在一个问题, 如果我们更改了我们的一个入口起点的名称,甚至添加了一个新的入口,会在构建时重新命名生成的 bundle,但是我们的 index.html 文件仍然引用旧的名称.
这就会导致index.html无法引入我们新生成的js,为了解决这个问题,我们可以使用HtmlWebpackPlugin插件
HtmlWebpackPlugin简化了HTML文件的创建,以便为webpack包提供服务.这对于在文件名中包含每次会随着编译而发生变化哈希的 webpack bundle 尤其有用. 可以让插件为你生成一个HTML文件,使用lodash模板提供自己的模板,或使用自己的loader
const path = require('path');
+ const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
+ plugins: [
+ new HtmlWebpackPlugin({
+ title: '管理输出'
+ })
+ ],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
clean-webpack-plugin
clean-webpack-plugin是一个流行的清理插件,它可以在每次运行打包命令时清空/dist文件夹,避免将上次打包遗留的文件和新生成的文件混杂在一起
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 注意在新版本的webpack里面要这么引入
+ const { CleanWebpackPlugin } = require('clean-webpack-plugin'); // 正确引入方式
// const CleanWebpackPlugin = require('clean-webpack-plugin'); // 错误引入方式
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
plugins: [
+ new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: '管理输出'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
1万+

被折叠的 条评论
为什么被折叠?



