将JS包引入到html文件
webpack根据入口文件,解析里面使用import或者require引入的模块,将引入的模块打包到一个js文件中。
步骤1完成了JS打包,需要引入到html文件中才能使用
需要将生成的js文件自动引入html文件中
使用到插件:
html-webpack-plugin
安装插件
1npm i html-webpack-plugin --save-dev配置 webpack.config.js
12345678910111213141516171819//+++//引入插件const HtmlWebpackPlugin = require('html-webpack-plugin');//+++const config = {entry:'./src/main.js',output: {filename:'bundle.js',path: path.resolve(__dirname,'dist')},//+++//配置插件//plugins,插件数组。需要使用的插件都添加到这个数组中plugins:[new HtmlWebpackPlugin()]//+++}更改main.js,以便查看效果
增加1document.body.style.background = 'red';执行
1npm run startdist目录下会生成:
bundle.js
index.html浏览器打开index.html,显示红色页面
index.html由 HtmlWebpackPlugin 插件自动生成,并将bundle.js插入到页面中使用自己的html文件
配置 HtmlWebpackPlugin123456789101112131415161718192021new HtmlWebpackPlugin({template:'index.html' //自定义html文件的路径和名称})```生成的js会自动插入到body标签的最后# 详细配置具体可参考 [github html-webpack-plugin](https://github.com/jantimon/html-webpack-plugin#)```jsnew HtmlWebpackPlugin({title:'test', //设置标题,默认为'Webpack App'filename:'index.html', //输出的文件名,默认为'index.html'template:'index.html', //模版文件名,默认为''templateParameters:{//模版中的参数配置testName:'123'},inject:true,//注入到页面中的位置,默认为true:注入到body标签底部minify:true //压缩,默认为false})
本文地址: http://gehaiqing.com/blog/2018/07/06/20180706-webpack-2-inject-html/