Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9042

【ECMAScript】importでSyntaxError

$
0
0

ECMAScriptの記法を学習していたところ、外部モジュールのimportで詰まったので解決策を残しておきます。

実行環境

  • Node.js : v12.12.0
  • IDE: WebStorm(2019.3.1)

ディレクトリ / ファイル

index.jsからadd.jsで定義した関数を使うだけの簡単なものです。

.├── add.js
└── index.js
index.js
import{add}from"./add.js";console.log(add(10,15));
add.js
exportfunctionadd(a,b){returna+b;}

なぜかimportの箇所SyntaxErrorとなる

実行時、エラーが出力されたので調べてみたところ、以下の対応が必要とのこと。

  • 実行時オプションに --experimental-modulesを指定する
  • ファイル拡張子を変更する(js -> mjs) or package.jsonを作成する

今回は拡張子は変えず package.jsonファイルを作成して対応。

(node:13761) ExperimentalWarning: The ESM module loader is experimental.
(node:13761) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
import { add } from "./add";^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:892:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at internal/main/run_main_module.js:17:11

エラー対応後

.├── add.js
├── index.js
└── package.json
package.json
{"type":"module"}

Node parameters--experimental-modulesを追加
webstorm.png

実行してみる

正常に実行できたようです。

/Users/xxxxx/.nodebrew/current/bin/node --experimental-modules /Users/xxxxx/WebstormProjects/untitled/index.js
(node:13854) ExperimentalWarning: The ESM module loader is experimental.
25

Process finished with exit code 0

参考

[Node.js の ESModules]
http://var.blog.jp/archives/80335431.html


Viewing all articles
Browse latest Browse all 9042