webpack打包html

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值