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()
  ]
}

猜你喜欢

转载自www.cnblogs.com/qfstudy/p/10747454.html