打字稿你导入 `lodash` -- 带有 `es2015` 模块吗?

Typescript do you import `lodash` -- with `es2015` modules?

它曾经有效,但现在我将我的项目更改为 ionic2@RC.0,其中包含新的 rollupes2015 bundling/modules。我无法正确获得 lodash

lodash 在那里,但在错误的地方 -- 我需要的方法在 _.default

npm 步骤

npm install lodash --save
npm install @types/lodash --save-dev --save-exact

javascript

import * as _ from "lodash";
console.log( Object.keys(_) )    // ["default", "__moduleExports"]
console.log(_.default.VERSION)   // 4.16.2

发生了什么事?

更新

import _ from "lodash";  // imports as lodash, not _

// Chrome debugger console:
console.log(_)      // VM2037:1 Uncaught ReferenceError: _ is not defined(…)
console.log(lodash) // function
console.log(Object.keys(lodash))  // returns: VM2075:1 ["templateSettings", "after", "ary", "assign", ...]

更新 2

也许是 Chrome Debugger + Rollup 的问题?我将我的代码更改为 import _ from "lodash";,它工作正常——除了在调试器控制台中...

    console.log(">>> _.keys(_): " + _.keys(_).slice(10, 20));
    // >>> _.keys(_): bindAll,bindKey,castArray,chain,chunk,compact,concat,cond,conforms,constant
    // and the _.sortBy() below works fine
    var sorted = _.sortBy(photos, function (o) {
        return o[sort.key];
    });

   // BUT, in the Chrome debugger (at breakpoint)
   console.log(_)      // VM2037:1 Uncaught ReferenceError: _ is not defined(…)

事实上,当我查看 main.js 而不是源地图时,我看到了 tree-shaking(?) 的迹象:

        console.log(">>> _.keys(_): " + lodash.keys(lodash).slice(10, 20));
        var sorted = lodash.sortBy(photos, function (o) {
            return o[sort.key];
        });

我的问题似乎是 Chrome 调试控制台,但我不确定如何解决它...

问题是您在导入中使用了 import * as。这不会 select 默认值。

改用导入默认值的语法:

import _ from "lodash"

Here is a link to the documentation

rollup 似乎尝试使用静态导入对包进行 tree-shaking。因此,它也需要一个 ES6 的 lodash 依赖项。尝试安装 lodash-es 包,然后导入它:

import _ from "lodash-es"