如何在Node.js REPL中导入ES模块?

时间:2019-02-20 10:54:22

标签: node.js import module

我有一个ES6模块right.mjs。将其作为node的参数执行效果很好:

$ node --version
v8.10.0
$ node --experimental-modules right.mjs
(node:4492) ExperimentalWarning: The ESM module loader is experimental.
executing right module

executing right module是模块的输出。

与此相反,REPL中的以下输入等待进一步的输入:

$ node --experimental-modules
> (node:4526) ExperimentalWarning: The ESM module loader is experimental.

> import 'right.mjs';
... 

我不明白为什么。

与以下相同:

> import './right.mjs';
... 

尝试require会导致:

> require('./right.mjs');
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/xxx/right.mjs
    at Object.Module._extensions..mjs (module.js:686:11)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)

那么,如何在Node.js REPL中导入ES模块?

3 个答案:

答案 0 :(得分:6)

在Node v14中是可能的,但是您需要使用formattedValue = ''; updateFieldValue($target: any) { const decimalValue = parseFloat($target.value.replace(/,/g, '')); if (decimalValue > 999) { this.formattedValue = this._getFormattedValue(); } else { this.formattedValue = decimalValue.toString(); } } private _getFormattedValue(): string { return DecimalPipe.prototype.transform(this.field.value || this.field.defaultValue, undefined, 'en-US'); } 函数,而不是import语句。

import

答案 1 :(得分:2)

目前这是不可能的。 ES模块应该从ES模块范围导入,而REPL不被认为是其中之一。随着时间的推移,这会有所改善,因为ES模块的支持是实验性的。在节点模块实现中,requireimport的使用是互斥的,REPL已使用require

预计REPL it isn't supported yet中将支持动态import,最新的Node 11版本会导致错误:

  

TypeError [ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING]:未指定动态导入回调。

答案 2 :(得分:1)

询问的内容(不是真正的REPL)不完全是问题,而是(使用node 12.6.0),可以通过--eval从命令行执行ESM代码:

  1. 首先,如果您的ES模块具有.js扩展名而不是.mjs,则将"type": "module"放在package.json中(请参阅https://nodejs.org/api/esm.html#esm_enabling)以允许节点处理JS文件作为模块
  2. 运行node --experimental-modules --input-type=module --eval 'code here'

例如,您可以将其别名为esmeval

alias esmeval='node --experimental-modules --input-type=module --eval'

然后您可以将其用作:

esmeval 'import { method } from "./path/to/utils.js"; console.log(method("param"))'

如果您仍不能使用节点12作为主要版本,但可以通过nvm进行安装,则将别名指向v12安装:

alias esmeval='/c/software/nvm/v12.6.0/node.exe --experimental-modules --input-type=module --eval'