webpack4打包html,html-webpack-plugin详解

打包html使用插件:html-webpack-plugin

安装

npm i --save-dev html-webpack-plugin

配置文件


const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    entry: __dirname+"/src/index.js", //入口文件,从项目根目录指定
    output: { //输出路径和文件名,使用path模块resolve方法将输出路径解析为绝对路径
        publicPath: __dirname + "/build", // js引用路径或者CDN地址
        path: path.resolve(__dirname, "build"), //打包后的js文件存放的地方 将js文件打包到build的目录
        filename: "main.js" //打包后输出的js的文件名 将入口文件index.js打包到build/main.js
    },
    devServer: {
        contentBase: './build',//默认webpack-dev-server会为根文件夹提供本地服务器,如果想为另外一个目录下的文件提供本地服务器,应该在这里设置其所在目录(本例设置到"build"目录)
        historyApiFallback: true,//在开发单页应用时非常有用,它依赖于HTML5 history API,如果设置为true,所有的跳转将指向index.html
        inline: true,//设置为true,当源文件改变时会自动刷新页面
        port: 8080//设置默认监听端口,如果省略,默认为"8080"
    },
    plugins: [
  	  new HtmlWebpackPlugin({
	    title: 'Custom template',
	    template: './src/index.html', //指定要打包的html路径和文件名
	    filename:'../index.html' ,//指定输出路径和文件名 
	    favicon:'./src/img/apple-touch-icon.png',//给生成的 html 文件生成一个标签<link rel="shortcut icon" href="apple-touch-icon.png">
	    hash: true,//给生成的 js 文件一个独特的 hash 值 <script type=text/javascript src=bundle.js?22b9692e22e7be37b57e></script>
	    showErrors:true,//webpack 编译出现错误
	    minify:{//对 html 文件进行压缩,minify 的属性值是一个压缩选项或者 false 。默认值为false, 不对生成的 html 文件进行压缩
                 removeComments:true, // 去除注释
                 collapseWhitespace: true //是否去除空格
             }
	  })
    ]
}

index.html

在html的title处填写<title><%= htmlWebpackPlugin.options.title %></title>打包后会自动附上new HtmlWebpackPlugin方法里面的title的值

猜你喜欢

转载自blog.csdn.net/qq_34035425/article/details/83042701