7
5

More than 5 years have passed since last update.

Node.jsでES Modules(export/import)ができなかったので軽く調べた

Posted at

概要

Node.jsでES Modulesを試そうとした時に、SyntaxErrorを吐いたのでちょっと調べてみました。

結論

.jsを.mjsにしてnodeでjsを実行する時に--experimental-modulesパラメータを与えるとES Moduleが使える。

コード

// app.js
import {
    log1,
    log2
} from './ex';
import {
    hoge
} from './class';
log1();
log2();
const obj = new hoge();
obj.say();
// ex.js
export function log1() {
    console.log('log1');
}
export function log2() {
    console.log('log2');
}
// class.js
export class hoge {
    say() {
        console.log('hoge->say()');
    }
}

実行結果

~/D/t/jsTest> node app.js
/Users/s-yoshida/Downloads/temp/jsTest/app.js:1
(function (exports, require, module, __filename, __dirname) { import {
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:83:7)
    at createScript (vm.js:267:10)
    at Object.runInThisContext (vm.js:319:10)
    at Module._compile (internal/modules/cjs/loader.js:684:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:774:12)
    at executeUserCode (internal/bootstrap/node.js:342:17)

import?何それ?オイシイノ?と仰ってる(´・ω・`)

調べる

node es module」でググると公式が出てくるので眺める。
ECMAScript Modules | Node.js v11.9.0 DocumentationEnablingのところに、

The --experimental-modules flag can be used to enable features for loading ESM modules.
Once this has been set, files ending with .mjs will be able to be loaded as ES Modules.

と書いてある...要約すると「--experimental-modulesフラグを指定するとES Moduleが有効になるよ」「.mjsファイルをES Modulesとしてロードできるよ」とのこと。なるほど。

手直しして動かす

.jsを.mjsに修正して動かす。

~/D/t/jsTest> node --experimental-modules app.mjs
(node:53346) ExperimentalWarning: The ESM module loader is experimental.
log1
log2
hoge->say()

やったぜ(๑•̀ㅂ•́)و✧

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5