webpack 的htmlwebpackplugin使用自定义模板

  htmlwebpackplugin这个插件能够用来生成静态的html文件。默认内部是经过后台来生成一个html的文件。固然也能够本身使用本身的文件来生成模板。能够支持.html文件。也可使用其余类型的模板。例如ejs。而ejs简单方便。很适合来生成咱们所需的静态文件。javascript

 htmlwebpackplugin的基本用法以下:css

  首先须要在webpack的配置中require进来或者用es6的import:html

     

const HtmlWebpackPlugin = require('html-webpack-plugin');

 而后在配置的plugins选项中引用插件:java

new HtmlWebpackPlugin({}),

支持的选项在 这里 能够查看 ,他支持生成多个index。只须要在plugins中屡次引入便可:webpack

注意:这样引入多个仍是只会生成默认的index.html.因此须要多个不一样的html时。每次引入都要单独的配置,引入html做为模板很简单。只须要提供相应的属性就能够。git

new HtmlWebpackPlugin({
            title:'my first webpack',
            template:'index.html'
 })

 而后是须要用ejs来生成须要的html文件,用ejs的话就须要相应的ejs-loader,不然你在ejs里面写<%=htmlwebpack.options.xx%>会报错。由于他处理不了ejs类型文件。在module里面加上对ejs类型文件的处理便可:es6

module: {
        rules: [
            {test:/\.ejs$/,use:['ejs-loader']},
            { test: /\.css$/, use: ['style-loader', 'css-loader'] },
            { test: /\.(gif|png|svg|jpg)/, use: ['file-loader'] }
        ]
    }

而后在htmlwebpackplugin的配置里面加上以下配置:github

  new HtmlWebpackPlugin({
//title title:
'my first webpack', //模板所在位置
template:
'index.ejs',
//其余任意数据 name:
'123124', data:'454564457' })

在index.ejs里面以下:web

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%=htmlWebpackPlugin.options.title%></title>
</head>
<body>
    <p><%=htmlWebpackPlugin.options.name%></p>
    <p><%=htmlWebpackPlugin.options.data%></p>
</body>
</html>

使用webpack编译生成文件以下:app

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>my first webpack</title>
</head>
<body>
    <p>123124</p>
    <p>454564457</p>
<script type="text/javascript" src="app.40d7ef6bd624409cbedf.js"></script></body>
</html>
相关文章
相关标签/搜索