有没有办法使用 'import' 而不是 'require' 从这个节点模块导入?

Is there a way to import from this node module with 'import' instead of 'require'?

我正在使用此节点模块 'deep-equal' (),到目前为止,我能够访问其中功能的唯一方法是使用 var equal = require('deep-equal');,如文档中所建议的。我通常使用 import 而不是 require,并且想知道是否可以将 import 与此模块一起使用。主要功能是从文件中导出的这一行:

var deepEqual = module.exports = function (actual, expected, opts) {...}

是否可以使用 import 导入此功能,或者是否只能使用 require

谢谢!

是的,你真的可以。

如果您使用的是 nodejs LTS,那么您必须对使用 import 的文件使用 .mjs 扩展名,并传递 experimental-modules 标志,同时运行 node 进程。

// foo.mjs
import equal from 'deep-equal';

node --experimental-modules foo.mjs

nodejs 12.3.0 开始,您可以简单地通过 experimental-modules。来自 docs

Once enabled, Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code

您还可以在 package.json:

中将 type 指定为 module
// package.json
{
  "type": "module"
}

来自文档

Files ending with .js or .mjs, or lacking any extension, will be loaded as ES modules when the nearest parent package.json file contains a top-level field "type" with a value of "module"