webpack打包html
一.多个js文件打包一个html文件
1.需要先配置好环境
a.先在终端安装好环境
npm install webpack -g
npm install webpack-cli -g
b.运行npm init -y得到package.json文件
运行npm install webpack --save-dev得到文件package-lock.json和node_modules
2.在package-lock.json文件中修改build,如图所示`
{
"name": "2.webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.28.2",
"webpack-cli": "^3.1.2"
},
"dependencies": {
"html-webpack-plugin": "^3.2.0"
}
}
3.创建webpack.config.js文件(该文件和package-lock.json文件同级),在该文件写入
var path = require('path');
var HtmlWebpackPlugin2 = require('html-webpack-plugin');
module.exports={
entry:{
index:"./src/index.js",
index2:"./src/index2.js"
},
output:{
path:path.resolve(__dirname,"dist"),
filename: '[name].bundle.js'
},
plugins:[
new HtmlWebpackPlugin2({
title:"denglongshun",
template:"./src/index.html"
})
]
}
4.创建src文件,在文件中创建1个index.html文件和两个js文件为index.js和index2.js文件,并在文件中输入你要输入的内容
5.建立html插件
npm install html-webpack-plugin
6.运行npm run build在会出现文件dist,里面会有打包好的文件
打开页面效果为
如果需要修改title以及需要对文件进行去空格和不必要的引号
可以将webpack.config.js文件修改为
var path = require('path');
var HtmlWebpackPlugin2 = require('html-webpack-plugin');
module.exports={
entry:{
index:"./src/index.js",
index2:"./src/index2.js"
},
output:{
path:path.resolve(__dirname,"dist"),
filename: '[name].bundle.js'
},
plugins:[
new HtmlWebpackPlugin2({
title:"haha",
minify:{
collapseWhitespace:true,
removeAttributeQuotes: true
},
template:"./src/index.html" ,
})
]
}
并且在src文件夹中的index.html的文件中title修改为
<head>
<meta charset="UTF-8">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
运行npm run build
生成
<!DOCTYPE html><html><head><meta charset=UTF-8><title>haha</title></head><body><div id=box>1111111</div><script type=text/javascript src=index.bundle.js></script><script type=text/javascript src=index2.bundle.js></script></body></html>