webpack html自动引入,webpack进阶【4】:打包后自动生成html [html-webpack-plugin插件]...

打包后自动生成html [html-webpack-plugin插件]

注意: 本进阶在webpack进阶【3】的基础上进行

一、为什么需要html-webpack-plugin插件

如果没有用插件,index.html中我们需要引入打包后的js文件,以后更多还需要引入css文件。

75933f721764

image.png

index.html引用的文件名要和webpack.config.js中output中fileName中的文件名要相同。

75933f721764

image.png

如果webpack.config.js中output中的fileName文件名修改了,index.html中引入的文件名也需要修改。

所以这时候我们需要引用 【html-webpack-plugin插件】,打包的时候【dist文件夹】自动生成【index.html】文件,并且会【index.html】会自动引入打包后的【js】。

二、下载插件【html-webpak-plugin】

cnpm i html-webpack-plugin

三、webpack.config.js 中引入 html-webpack-plugin 插件并进行配置

const path = require('path'); // 引入path模块

const HtmlWebpackPlugin = require('html-webpack-plugin'); // 引入自动生成 html 的插件

// 配置webpack的配置文件,需要将配置的对象导出,给webpack使用

module.exports = {

// 1. 打包入口,从哪个文件开始打包

entry: './src/main.js',

// 2. 打包的文件放在哪

output:{

// 打包的文件输出的目录(输出的目录必须是一个绝对路径),这里也可以写成path:path.join(_dirname, 'dist')

path: path.join(__dirname, './dist'),

// 打包后的文件名叫什么

filename: 'bundle.js'

},

// 3. 打包的模式: production 生产模式(打包后的文件或压缩) development(开发模式,不压缩)

mode: 'development',

// 4. 插件配置

plugins: [

// 我们要把哪个目录下的 html 进行自动生成。

new HtmlWebpackPlugin({template: './public/index.html'})

],

}

四、执行打包命令

cnpm run build

五、打包后,dist中有html文件和js文件

75933f721764

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值