webpack--指南3--管理输出

xiaoxiao2021-02-28  87

HtmlWebpackPlugin插件

如果我们更改了我们的一个入口起点的名称,甚至添加了一个新的名称,会发生什么?生成的包将被重命名在一个构建中,但是我们的index.html文件仍然会引用旧的名字,我们用HtmlWebpackPlugin来解决这个问题;

npm install --save-dev html-webpack-plugin const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { app: './src/index.js', print: './src/print.js' }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') }, plugins: [ new HtmlWebpackPlugin({ title: 'Output Management' }) ] };

这个插件安装以后,虽然在dist文件夹我们已经有index.html这个文件,然而 HtmlWebpackPlugin 还是会默认生成index.html文件。这就是说,她会用新生成的index.html把我们原来的替换;如果你在代码编辑器中 index.html 打开,你就会看到 HtmlWebpackPlugin 创建了一个全新的文件,所有的 bundle 会自动添加到 html 中。

clean-webpack-plugin

由于过去的指南和代码实例遗留下来,导致我们的。dist文件夹相当杂乱,webpack会生成文件,然后将这些文件放置在dist文件夹中,但是webpack无法追踪到哪些文件是实际在项目中用到的;通常在每次构建前清理dist文件夹是比较推荐的做法,因此只会生成用到的文件,clean-webpack-plugin是一个比较普及的插件;让我们来安装配置

npm install clean-webpack-plugin --save-dev const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); + const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { entry: { app: './src/index.js', print: './src/print.js' }, plugins: [ + new CleanWebpackPlugin(['dist']), new HtmlWebpackPlugin({ title: 'Output Management' }) ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } };

现在执行 npm run build,再检查 /dist 文件夹。如果一切顺利,你现在应该不会再看到旧的文件,只有构建后生成的文件! webpack及其插件似乎知道应该哪些文件生成;答案是通过manifest,webpack能够对(你的模块映射到输出bundle的过程)保持追踪;

转载请注明原文地址: https://www.6miu.com/read-53650.html

最新回复(0)