webpack入门第四节:自动化生成项目中的HTML页面(下)

自动化生成项目中的HTML页面(下)

1:这里很关键,首先讲一下怎么自动生成HTML页面,首先我们创建3个文件 a.js b.js c.js,自动生成页面无非就是重新实例化htmlWebpackPlugin,但是在参数上会有所调整,请仔仔细细的看下面几张图,尤其是HTML页面,以及webpack.config.js中的配置

HTML:请注意这里不需要任何script脚本引入代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><%= htmlWebpackPlugin.options.title %></title>
    <!-- 下面这行代码对应的是main文件打包生成以后的地址 -->
</head>
<body>
    <!-- 我是一行注释 -->
</body>
</html>

webpack.config.js的配置,这里非常非常需要关注的一点是:chunks,这个东西,对应的是打包后的js的文件路径,仔细看注释!,当然你也可以把chunks:['a','b','c']来引入js的脚本,以及还有一个excludeChunks:['a','b'],意为排除a和b的打包后的脚本

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

    module.exports = {
        entry: {
            a: './src/script/a.js',
            b: './src/script/b.js',
            c: './src/script/c.js'
        },
        output: {
            path: __dirname + '/dist',//调整目录,项目生成在此文件夹下,这样index就会生成在dist目录下
            filename: 'js/[name]-[hash].js',//在js目录下生成js文件
            publicPath: 'https://cdn.com'
        },
        plugins: [
            new htmlWebpackPlugin({
                filename: 'a.html',//生成文件名
                template: 'index.html',//调用的html模板
                inject: 'body',//请大家注意,这里一定要改成false,不然默认会在head中又生成2个打包文件
                title: 'this is a.html',//在index中我们会利用模板语法来导入title
                //请大家一定要认真看这一条,chunks是参数的属性,前面讲到过,在调用的时候,下面的方式是不可行的,
                //因为下面的模板语法获取到的是main.js打包后的路径,而此时,我们已经没有main这个文件了,取而代之的是
                //a.js,b.js,c.js,我们需要在插件这里填写chunks:[]这个属性,那么HTML中怎么填写模板语法呢?
                //<script src="<%= htmlWebpackPlugin.files.chunks.main.entry %>"></script>
                chunks:['a']
            }),
            new htmlWebpackPlugin({
                filename: 'b.html',
                template: 'index.html',
                inject: 'body',
                title: 'this is b.html',
                chunks:['b']
            }),
            new htmlWebpackPlugin({
                filename: 'c.html',
                template: 'index.html',
                inject: 'body',
                title: 'this is c.html',
                chunks:['c']
            })
        ]
    }

猜你喜欢

转载自blog.csdn.net/weixin_42450794/article/details/81706632