乐趣区

webpack4.0入门学习笔记(二)

代码下载:github

html-webpack-plugin的使用

安装
npm i html-webpack-plugin -D

在 webpack4.0 入门学习笔记 (一) 中,我们是自己在打包目录下创建 index.html 对打包后 js 文件进行引用。

html-webpack-plugin插件可以根据对应的模板在打包的过程中自动生成 index.html,并且能够对打包的文件自动引入。

webpack.config.jsplugins中配置如下

const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')

module.exports={
  entry: {main: './src/index.js'},
  // 打包完成后文件存放位置配置
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname,'dist')
  },
  
  plugins: [
    new htmlWebpackPlugin({template: './index.html'})
  ]
}

在终端执行 npm run start,打包完成后在dist 目录下自动生成 index.html 文件,并且还自动引入所有文件。

clean-webpack-plugin的使用

每次打包生成的 dist 目录,如果改一次代码,都得要删除一次 dist 目录,这样很麻烦,可以通过 clean-webpack-plugin 在每次打包的时候自动清空 dist 目录。

安装
npm i clean-webpack-plugin -D

webpack.config.jsplugins中配置如下

const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')
const cleanWebpackPlugin = require('clean-webpack-plugin')

module.exports={
  entry: {main: './src/index.js'},
  // 打包完成后文件存放位置配置
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname,'dist')
  },
  
  plugins: [
    new htmlWebpackPlugin({template: './index.html'}),
    new cleanWebpackPlugin()]
}
退出移动版