【问题标题】:Difference importing template from lodash and lodash/template?从 lodash 和 lodash/template 导入模板的区别?
【发布时间】:2017-04-27 13:07:07
【问题描述】:

像这样从 lodash 导入“模板”有区别吗:

import { template } from 'lodash';

或者像这样:

import template from 'lodash/template';

第一种方法可以正常工作,但第二种方法在我在模板中使用 _.isString 等其他 lodash 函数时会抛出 TypeError。

未捕获的类型错误:_.isString 不是函数 在 eval (eval at (template.js:225), :10:13)

如果我在 eval 中调试,_(下划线)对象如下所示:

Object {escape: function}
    escape: function escape(string)
    __proto__: Object

除转义函数外为空?

我想使用 lodash/core 和 cherrypick 非核心函数,例如“模板”,但这很难。

环境:

  • Webpack 1.13.0
  • 通天塔 6.24.1
  • 骨干网 1.3.3
  • Lo​​dash 4.17.4

【问题讨论】:

  • 对我来说 import template from 'lodash/template' 不起作用:Error: 'default' is not exported by node_modules\lodash.template\index.js

标签: javascript templates import lodash


【解决方案1】:

我通过在 _.template 中使用 templateSettings.imports 并基本上将 lodash 导入到模板处理 eval 中找到了一种解决方法。

const templateSettings = { imports: { _: _ } };
const processedTemplate = template(templateToProcess, templateSettings)(data);

这里是模板和模板设置的 Lodash 文档: https://lodash.com/docs/latest#template

我仍然不知道为什么在使用欢快的模板导入时,下划线全局在 eval 中是空的...

【讨论】:

    【解决方案2】:

    对于碰巧遇到这种情况的其他人,即使是在 2020 年:

    Webpack、babel 等结合使用它们“预编译”的混蛋 lodash(以及所有其他库)。构建模板时,您无法使用预期的对象实例和行为。例如,_.forEach 可能会在内存中“优化”为lodash_forEach__WEBPACK_IMPORTED_MODULE_0___default。因此,如果您尝试在任何未“预编译”到同一 babel 脚本管道中的脚本中使用预期的 lodash 实例化“_”,它将不可用(我认为这对 SPA 有意义)。

    为了“使用”任何“优化”的行为,您需要明确地传入该行为。这样,当 webpack 和 babel 做他们的事情时,正确的函数就会被投射到模板运行时中。

     var template = $('#template').html(),
            compiled = _.template(template, { 'imports': { 'each': _.forEach } });
    

    然后在你的模板中:

    <% each(items, function(item) { %><li><%- item %></li><% }); %>
    

    【讨论】:

      猜你喜欢
      • 2019-04-18
      • 1970-01-01
      • 2023-02-20
      • 2018-05-31
      • 1970-01-01
      • 2023-03-20
      • 2021-05-12
      • 1970-01-01
      • 2021-03-06
      相关资源
      最近更新 更多