Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

HtmlWebpackPlugin使用模板引擎进行变量动态注入 #51

Open
jiangjiu opened this issue Sep 20, 2018 · 2 comments
Open

HtmlWebpackPlugin使用模板引擎进行变量动态注入 #51

jiangjiu opened this issue Sep 20, 2018 · 2 comments

Comments

@jiangjiu
Copy link
Owner

HtmlWebpackPlugin使用模板引擎进行变量动态注入

HtmlWebpackPlugin是一个用来生成html页面的webpack插件,目前最新已经到了4.0.0-alpha.2。

说起来这个版本的tapable生命周期有些问题(见jantimon/html-webpack-plugin#1049),不过不要在意这些细节,最近工作中需要对多页应用做一些动态注入变量的操作,在此总结一下。

背景

多页面应用又称MPA,在构建编译的时候比起单页应用来说更为复杂。

对于生成html来说,不同的页面html,90%的内容是基本一致的,但是有10%的内容,每个页面需要有自己的区别。


比如上图中的标题👆🏻。

问题

当我们确认,MPA的模板统一为一个base.html后,问题就来了:

如何设计业务开发者的操作路径or配置,可以提高开发效率又拥有足够的扩展性呢?

业务开发者的配置

按照约定大于配置的思想,我们要在多页面入口配置中,混入可扩展的配置项:

/**
 * @typedef {Object}pageInfo
 * @property {string} path
 * @property {string} title
 * @property {string} pageDataApiPath
 */

/**
 * @exports
 * @readonly
 * @type {Object.<string,pageInfo>}
 */
module.exports = {
    // 活动主页
    home: {
        path: '/home',
        title: '测试主页',
        pageDataApiPath: '/api/index'
    },
    // 分享页
    share: {
        path: '/share',
        title: '测试分享页',
        pageDataApiPath: '/api/index'
    }
};

业务开发者只需在这个入口文件中配置好各个页面的标题等相关信息即可,其余就无需关心了。

那么,构建工具是如何实现动态注入的呢?

构建


HtmlWebpackPlugin内置了ejs模板引擎解析,可以通过变量替换拿到相应的值:

// 注意:base.html 改名成 base.ejs
// base.ejs
...
    // 注意变量名大小写
    <title><%= htmlWebpackPlugin.options.title %></title>
...

然后我们在插件的位置注入title:

// webpack.config.js
...
plugins: [
    new HtmlWebpackPlugin({
        {
            filename: `${name}.html`,
            template: `${TEMPLATE_PATH}/base.ejs`,
            inject: 'body',
            alwaysWriteToDisk: true,
            chunks: [name],
            prefetch: false,
            // 在这里传入title及其他配置项
            title,
            ...
        }
    })
]
...

总结

这样,就完成了动态变量注入。

通过这个特性,我们可以在关键位置暴露足够的钩子,业务开发者可以按需使用了。

@mewang-tableau
Copy link

@DevinWell1ee
Copy link

你好,我发现升级htmlwebpackplugin v4 之后,不能注入成功呢

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

3 participants