Node.js 4.2.1中的导出和导入

Export and Import in Node.js 4.2.1

本文关键字:导入 js Node      更新时间:2023-09-26

我有两个文件。

other.js

export var test = 12;
export var test2 = 'testing';

main.js

import other from "other.js";
console.log(other);

我写node main.js。我期待这个:

{
    test: 12,
    test2: 'testing'
}

但我得到了一个错误:

(function (exports, require, module, __filename, __dirname) { import oth from "other.js";
                                                              ^^^^^^
SyntaxError: Unexpected reserved word

Node.js版本4.2.1。怎么了?

Node不支持importexport(谁知道呢)。看见https://nodejs.org/en/docs/es6/以获取支持功能的列表。

您要么需要继续使用CommonJS模块,要么使用像Babel这样的transiler。

您需要导入所有内容并为它们分配一个别名。。。

但如果没有Transpiler,你就无法做到这一点,es6模块不可用。。。

import * as other from './other.js';
console.log(other);