节点-从另一个包中的模块导入类

Som*_*ser 5 javascript import node.js

我正在使用Node.js编写应用程序。具体来说,我正在使用Node v10.3.0。该应用程序位于的目录中./my-module-console/index.js。这个应用程式的的package.json档案位于./my-module-console/package.json。此应用程序引用了中定义的类./my-module/items/。应该注意的是,它my-module代表了自己的包装。该软件包在中定义./my-module/package.json。index.js中的代码如下所示:

'use strict';

import { Item } from '../my-module/items/item.js';

async function entry() {
  let item = await Item.FindById(1);
  console.log(item);
}

entry();
Run Code Online (Sandbox Code Playgroud)

当我尝试运行此命令时,出现以下错误:

import { Item } from '../my-module/items/item.js';
       ^
SyntaxError: Unexpected token {
Run Code Online (Sandbox Code Playgroud)

我的进口货单有什么问题?在我看来,这是正确的。我误会了吗?

item.js

class Item {
    constructor() {}

    async static FindById(id) {
      console.log('finding item by id: ' + id);
    }
};

module.exports = Item;
Run Code Online (Sandbox Code Playgroud)

谢谢!

evg*_*hev 5

正如@jsur 所提到的,ES 模块仍处于试验阶段。但是如果你想使用它们,你必须添加--experimental-modules. 如果你仍然想使用 ES 模块,那么你必须将 .js 重命名为 .mjs以及 item.js,它现在是 commonJS 样式,必须更改为 ES Modules + 其他小修复。而且您实际上不必使用“使用严格”,默认情况下它是严格的。所以最后它应该是这样的:

索引.mjs

import { Item } from '../my-module/items/item';

async function entry() {
  let item = await Item.FindById(1);
  console.log(item);
}

entry();
Run Code Online (Sandbox Code Playgroud)

项目.mjs

export class Item {
    constructor() {}

    static async FindById(id) {
      console.log('finding item by id: ' + id);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以现在就去做node --experimental-modules index.mjs,你就可以开始了。