Handlebars自定义助手 - 迁移到Webpack

4
我们有一个基于backbone、marionette和handlebars的应用程序,没有导入/导出或要求方法,由grunt管理,我们正在尝试迁移到webpack。
我在处理handlebars的自定义助手时遇到了问题。
我们助手的代码:
'use strict';

function I18n() {
    this.constructor(arguments);
}

I18n.prototype = {

    constructor: function () {
        ...some stuff

    }

    get: function () {
        ...some stuff
    }
    ...some other functions
}

ourNameSpace.I18n = new I18n();

这个函数是包含在一个文件中的,可以全局加载:

Handlebars.registerHelper('i18n', _.bind(ourNameSpace.I18n.get, ourNameSpace.I18n));

然后我们在模板中像这样使用它:
{{i18n "LblEmail"}}

我尝试使用handlebars-loader,并将以下查询对象添加到webpack.config中以将其添加到捆绑包中:

{ 
    test: /\.hbs$/, 
    use: {
        loader: 'handlebars-loader',
        query: { 
            helperDirs: [
                path.resolve(__dirname, 'public/assets/js/common/i18n/')
            ]
        }
    }
}

Webpack会在打包中加入我们的辅助代码,但当这些代码在模板中被调用时,我遇到了这个错误:

Uncaught TypeError: __default(...).call is not a function

Webpack 生成的捆绑包中调用的代码如下:
...
    + alias2(__default(__webpack_require__(2)).call(alias1,"LblEmail",{"name":"i18n","hash":{},"data":data}))
...

在第二次尝试中,我还尝试在 helper 文件中添加导出功能,即使我们的应用程序尚未使用导入/导出方法。将以下内容添加到 helper 文件末尾:
export default I18n

这样修复了错误,但是助手似乎不起作用,因为页面上所有的文本都是空的(而不是显示i18n翻译或键)。

有人用handlebars自定义助手做过类似的迁移吗?或者知道我如何重构它,使Webpack可以正确处理它并且捆绑包可以正确执行它吗?

1个回答

1

几个月后,我回答了自己的问题,我通过以下方式解决了我们的问题:

  • I rewrite our old legacy helper (with custom functions) by creating more modern ones (three, for our three functions that was in legacy helper) relying on I18nJS:

    import I18nJs from 'i18n-js';
    const I18n = key => I18nJs.t(key);
    export default I18n;
    
  • It is loaded by webpack with handlebars loaders like this :

    {
        test: /\.hbs$/,
        use: {
            loader: 'handlebars-loader?runtime=handlebars/runtime',
            query: {
                helperDirs: [path.resolve(__dirname, 'src/js/common/i18n/helper')],
                inlineRequires: '/images/',
                precompileOptions: {
                    knownHelpersOnly: false,
                },
            },
        },
    }
    
  • And in our template we did not have to change anything to use it :

    <label>{{i18n "LblEmail"}}</label>
    

然而,要在JavaScript文件中使用本地化,我们需要进行一些更改:

  • I created a "helper" (not handlebar helper) implementing same logic than handlebars helper :

    import I18nJs from 'i18n-js';
    
    const I18n = {
        get(key) {
            return I18nJs.t(key);
       },
    
       ... some other functions
    };
    export default I18n;
    
  • We import this file and use its function as usual in modern stacks :

    import I18n from '../common/i18n/I18nSt';
    ...
    console.log(I18n.get('PasswordMissing'));
    

因此,在我们的js文件中调用翻译函数时,我们需要进行小的重构。以前是这样的:

console.log(OurNamespace.I18n.get('PasswordMissing'));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接