Webpack中Plugins的用法(学习篇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') 
  }
}

执行打包:

npm  run  build

打包成功之后,发现dist目录下自动多出index.html文件。内容如下:

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

  • 第一步:会先生成一个html模板。
  • 第二部:会把打包生成的bundle.js注入到html的模板中。

第二个:clean-webpack-plugin

安装:

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文件,打包完成后发现,第一次打包生成的文件已被删除,替换成了新打包生成的文件。由此可以看出:cleanWebpackPlugin插件的作用就是:当我们在打包之前,清除dist目录下的所有内容。

总结: plugin插件的作用就是,可以在webpack运行到某个时刻的时候,自动的帮我们做一些事情。类似于我们使用框架中的生命周期函数。(这里只用到了插件里的个别配置项,更多配置项请参考webpack官方文档)?

发布了54 篇原创文章 · 获赞 22 · 访问量 7250

猜你喜欢

转载自blog.csdn.net/Riona_cheng/article/details/100199759