webpack---htmlWbpackPlugin插件在webpack中的应用

来源:互联网 发布:学完c语言之后学java 编辑:程序博客网 时间:2024/06/14 00:33

安装

cnpm install html-webpack-plugin

配置

title://生成的html文件的titlefilename://生成的html文件名字template://webpack引入的源html文件,2.0允许使用任何loader:直接使用字符串路劲(./index.html);前置loader(!!handlebars!./index.hbs);配置module.loader使用。inject: //添加位置:false-不添加,true-自动添加,head-添加至头部,body-添加至bodyfavicon://图标路径minify://{options},collapseWhitespace压缩去除空格,minifyJS压缩JS等等;hash://true代表给所有webpack打包的css js文件添加hash值,false反之cache://true代表仅打包更改的文件showError://true时候错误信息将会被备注于html中chunks://当前htmlWebpackPlugin对象中引入当前html文件所需的chunk块;chunksSordMode://分类excludeChunks://除了value(chunk数组)值外都引入;xhtml://默认false

使用

webpack.config.js:

const htmlWebpackPlugin=require('html-webpack-plugin');const path=require('path');module.exports={    entry:'./src/a.js',    output:{        path:path.resolve('./dist'),        filename:'js/bundel.[name].js'    },    plugins:[        new htmlWebpackPlugin({            template:'a.html',            filename:'a1.html',        })    ]}

a.html:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title></title></head><body></body></html>

运行webpack,dist目录下得到a1.html:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title></title></head><body><script src='./dist/bundel.a.js'></script></body></html>

绑定数据

htmlwebpackplugin插件支持在源html文件中像template语法一样给视图绑定数据

index.html:

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

webpack.config.js:

const path=require('path');const htmnlWbpackPlugin=require('html-webpack-plugin');module.exports={    entry:'./src/script/b.js',    output:{        path:path.resolve('./dist'),        filename:'js/[name].bundle.js',    },    plugins:[        new htmnlWbpackPlugin({            template:'index.html',            filename:'home.html',            inject:false,            title:'webpack',            data:'aaaaaa'        })    ]}

运行webpack,得到home.html:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>webpack</title></head><body>aaaaaa</body></html>,

多组html打包

webpack.config.js:

const path=require('path');const htmnlWbpackPlugin=require('html-webpack-plugin');module.exports={    entry:{page1:'./src/script/b.js',            page2:  ['./src/script/main.js','./src/script/a.js']           },    output:{        path:path.resolve('./dist'),        filename:'js/[name].[hash].js',        publicPath:'http://cdn.com/'    },    plugins:[        new htmnlWbpackPlugin({            template:'index.html',            filename:'home.html',            chunk:['page1','page2'],            title:'webpack is good',            data:'aaaaaa'        }),        new htmnlWbpackPlugin({            filename:'product.html',            template:'pro.html',            excludeChunks:['page2']        })    ]}
原创粉丝点击