How to import an ES module in Node.js REPL?

后端 未结 3 1977
离开以前
离开以前 2020-12-09 09:28

I have an ES6 module right.mjs. Executing it as a parameter to node works well:

$ node --version
v8.10.0
$ node --experimental-modu         


        
3条回答
  •  暖寄归人
    2020-12-09 10:21

    Not precisely what was asked about (not really REPL), but (using node 12.6.0), it is possible to execute ESM code from command line via --eval:

    1. First, if your ES modules have .js extension instead of .mjs, put "type": "module" in package.json (see https://nodejs.org/api/esm.html#esm_enabling) to allow node treating JS files as modules
    2. Run node --experimental-modules --input-type=module --eval 'code here'

    You could alias this as esmeval for example:

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

    And then you can use it as:

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

    If you can't use node 12 yet as a primary version, but can in install via nvm, make the alias point to the v12 installation:

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

提交回复
热议问题