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

问题描述 投票:0回答:5

我有一个 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` is the output of the 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 模块?

node.js import module
5个回答
77
投票

在 Node.js v14 中这是可能的,但您需要使用

import
运算符,而不是
import
声明。

$ node

Welcome to Node.js v14.4.0.
Type ".help" for more information.
> let myModule;
undefined
> import("./my-module.js").then(module => { myModule = module });
Promise { <pending> }
> myModule.foo();
"bar"

60
投票

目前不可能。 ES 模块应该从 ES 模块范围导入,而 REPL 不被视为之一。这会随着时间的推移而改善,因为对 ES 模块的支持是实验性的。

require
import
在 Node.js 模块实现中是互斥的,并且 REPL 已经使用了
require

从 Node.js 13 开始,REPL 支持动态

import

。使用 
node --experimental-repl-await
,它是:

await import('./right.mjs');
    

47
投票
使用支持顶级等待的 Node.js v16.9.1,它变得更加简单:

let { date } = await import('quasar') // module under node_modules, or your own one, etc. date.getWeekOfYear(new Date())
    

12
投票
这并不完全是所问的问题(不是真正的 REPL),但是(使用 Node.js 12.6.0),可以通过

--eval

:
从命令行执行 ESM 代码

    首先,如果您的 ES 模块具有
  1. .js 扩展名而不是 .mjs,请将 "type": "module"
     放入文件 
    package.json(请参阅 模块:ECMAScript 模块,启用)以允许 Node.js将 JavaScript 文件视为模块
  2. 奔跑
  3. 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"))'


如果您还不能使用 Node.js 12 作为主要版本,但可以通过

nvm

 安装,请将别名指向 v12 安装:

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


    


0
投票
在 REPL 中使用模块的一些谷歌搜索将我带到这里,这对我有用:

npm install -g libphonenumber-js​ node​ > let lib = require('/opt/homebrew/lib/node_modules/libphonenumber-js') > lib.isValidPhoneNumber('+97412345678') false > lib.isValidPhoneNumber('+15625551234') true
    
© www.soinside.com 2019 - 2024. All rights reserved.