webpack模块工厂-Webpack 中插件的使用(学习第 8 部分)

分享一下两个项目中常用的插件以及使用方法。

第一个:html-webpack-plugin

安装:

npm  i  html-webpack-plugin  -D

webpack.config.js 配置:

// 在这里做打包配置
const path = require('path'); // 引入node的path模块(loader模块)
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 引入插件
// Common.js语法
module.exports = {
  mode: 'development',
  devtool: 'cheap-module-eval-source-map',
  entry: {
    main: './src/index.js'
  },
  plugins: [new HtmlWebpackPlugin({ 
    template: './src/index.html'
  })],
  output: {
    filename: 'bundle.js', // 打包之后的输出文件
    path: path.resolve(__dirname, 'dist') 
  }
}

执行打包:

模块工厂技术员_模块工厂生产的常用设备_webpack模块工厂

npm  run  build

打包成功后发现dist目录下手动添加了index.html文件。 内容如下:

webpack模块工厂_模块工厂技术员_模块工厂生产的常用设备

由此可以看出,html-webpack-plugin插件在打包完成后会自动生成一个html文件,并将打包生成的js手动导入到html文件中。 打包完成后生成的html是使用模板中配置的html作为模板生成的。 这里运行的步骤是:

第二个:clean-webpack-plugin

安装:

模块工厂生产的常用设备_模块工厂技术员_webpack模块工厂

npm  i  clean-webpack-plugin  -D

webpack.config.js 配置:

// 在这里做打包配置
const path = require('path'); // 引入node的path模块(loader模块)
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// Common.js语法
module.exports = {
  mode: 'development',
  devtool: 'cheap-module-eval-source-map',
  entry: {
    main: './src/index.js'
  },
  plugins: [new HtmlWebpackPlugin({ 
    template: './src/index.html'
  }), new CleanWebpackPlugin()],
  output: {
    filename: 'dist.js', // 打包之后的输出文件为dist
    path: path.resolve(__dirname, 'dist') 
  }
}

执行打包:

npm  run  build

在配置项中,我们将打包的js输出文件由刚才的bundle.js改为dist.js文件。 打包完成后,我们发现第一个打包生成的文件已被删除,并替换为新打包的文件。 文档。 从这里可以看出webpack模块工厂,cleanWebpackPlugin插件的作用就是在我们打包之前清除dist目录下的所有内容。

总结:插件的作用是当webpack运行到某个点的时候webpack模块工厂,自动为我们做一些事情。 类似于我们在框架中使用生命周期函数的方式。 (这里只用到了插件中的部分配置项,更多配置项请参考webpack官方文档)