webpack打包(主要是处理html文件),并启动服务器

这篇文章主要说一下,如何在webpack打包过程中,处理html文件。

项目目录结构

现在需要,通过webpack打包后,把所有的打包结果放在项目目录下的build目录下,直接启动webpack-dev-server进行运行。

一、安装插件:

1、ExtractTextPlugin:  npm i  extract-text-webpack-plugin --save-dev

2、html-webpack-plugin:npm i  html-webpack-plugin  --save-dev

二、在webpack.config.js中增加如下代码:

 

const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    
    …………………………省略部分配置…………………………

	plugins:[   
		//对html模板进行处理,生成对应的html,引入需要的资源模块
		new HtmlWebpackPlugin({
			template:'./index.html',//模板文件,即需要打包和拷贝到build目录下的html文件
			filename:'index.html',//目标html文件
			chunks:['useperson'],//对应加载的资源,即html文件需要引入的js模块
			inject:true//资源加入到底部,把模块引入到html文件的底部
		})
  ]
}

三、最终的webpack.config.js的代码

 

const path = require('path');
const webpack = require('webpack')
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
	mode:"development",
	//入口文件(要打包的文件)
	entry:{
		"useperson":"./useperson.js"
	},

	//出口文件(打包的结果)
	output:{
		"path":__dirname+"/build/",
		"filename":"[name].bundle.js"
	},
	//启动服务
	devServer:{
		host:"localhost",
		port:"8080",
		contentBase:__dirname+"/build"
	},
	module: {
        //加载器配置
        rules: [
            { 
				test: /\.js$/, 
				loader: 'babel-loader',
				exclude: /node_modules/, //排除掉node_modules下的js文件,即不解析这个文件夹下的js文件
				query: {
				 presets: ['latest'] //按照最新的ES6语法规则去转换,可以把这个写在预设(.babelrc)文件里
				}
			},
			
        ]
    },
	plugins:[   
		//对html模板进行处理,生成对应的html,引入需要的资源模块
		new HtmlWebpackPlugin({
			template:'./index.html',//模板文件,即需要打包和拷贝到build目录下的html文件
			filename:'index.html',//目标html文件
			chunks:['useperson'],//对应加载的资源,html文件需要引入的js模块
			inject:true//资源加入到底部,把模块引入到html文件的底部
		})
  ]
}

四、执行webpack命令

         打包成功

五、执行webpack-dev-server启动服务器。

 

六、你也可以把webpack和webpack-dev-server一次性执行。需要在package.json里写上如下代码(npm script):

 "scripts": {
    "dev":"webpack && webpack-dev-server",
    …………………………………………
  },

此时,直接在命令行输入:npm run dev 就可以把webpack和webpack-dev-server两个命令一次性执行了。

 

七、在浏览器中输入: localhost:8080/index.html就可以看到结果了。

 

八、附:useperson.js和index.html的代码

useperson.js

document.write("hello");

index.html的代码(空的html文件):

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
</head>
<body>

</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值