html4模板,webpack4.x实战三,html模板

怎么动态的生成html文件呢?使用插件html-webpack-plugin。

html模板

安装插件 html-webpack-plugin

安装html-webpack-plugin

npm install --save-dev html-webpack-plugin

添加模板文件

在src目录下创建template目录,然后在template目录创建index.html文件

src目录结构

src

├── css

│   └── style.css

├── js

│   └── app.js

└── template

└── index.html

复制代码

index.html内容

webpack html

复制代码

html-webpack-plugin使用

修改后webapack.config.js内容

const path = require('path');

var htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

mode: 'development',

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

output: {

path: path.resolve(__dirname, 'dist'),

filename: 'js/app.bundle.js'

},

module: {

rules: [

{

test: /\.css$/,

use: [{ loader: 'style-loader' }, { loader: 'css-loader' }]

}

]

},

plugins: [

new htmlWebpackPlugin({

filename: 'index.html',

template: './src/template/index.html'

})

]

};

复制代码

plugins:webpack插件配置

new htmlWebpackPlugin({

filename: 'index.html',

template: './src/template/index.html',

})

复制代码

filename:打包后文件名称

template:模板文件路径

执行命令npm run webpack

浏览器访问 dist/index.html693156431d8a30ce61a6c077f93f1260.png

向html模板传递参数

html-webpack-plugin其他参数

修改后webapack.config.js内容

const path = require('path');

var htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

mode: 'development',

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

output: {

path: path.resolve(__dirname, 'dist'),

filename: 'js/app.bundle.js'

},

module: {

rules: [

{

test: /\.css$/,

use: [{ loader: 'style-loader' }, { loader: 'css-loader' }]

}

]

},

plugins: [

new htmlWebpackPlugin({

filename: 'index.html',

template: './src/template/index.html',

title: 'this is webpack title'

})

]

};

复制代码new htmlWebpackPlugin({

filename: 'index.html',

template: './src/template/index.html',

title: 'this is webpack title'

})

复制代码

title:自定义参数

修改index.html

复制代码

执行命令npm run webpack

浏览器访问 dist/index.html72577a600b296b2cf2b5cc8a757c5122.png

总结

安装插件html-webpack-plugin npm install --save-dev html-webpack-plugin

html-webpack-plugin使用

var htmlWebpackPlugin = require('html-webpack-plugin');

复制代码

module.exports添加plugins,实例化htmlWebpackPlugin对象

plugins: [

new htmlWebpackPlugin({

filename: 'index.html',

template: './src/template/index.html',

title: 'this is webpack title'

})

]

复制代码

filename:打包后文件名称

template:模板文件路径

其他参数:可以向html模板中传递参数,html模板中变量调用方法

思考:

如何分开打包css和js,生成不同的文件?

因为浏览器会缓存js和css,每次修改好了js和css,需要强制刷新浏览器;如何打包生成不同的文件名?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值