JavaScriptには他のファイルで定義されたリソースを利用するための仕組みとして import/exportがある。 exportを利用するためには、ソースファイルがモジュールである必要がある。
ソースファイルで export 宣言を使用するためには、そのファイルはランタイムによってモジュールとして解釈される必要があります。
モジュールとして宣言していない場合は SyntaxError: Cannot use import statement outside a module
になる。
$ node debug.js (node:9940) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. (Use `node --trace-warnings ...` to show where the warning was created) /home/thaim/work/debug.js:1 import { sample } from "./test.js"; ^^^^^^ SyntaxError: Cannot use import statement outside a module at internalCompileFunction (node:internal/vm:77:18) at wrapSafe (node:internal/modules/cjs/loader:1288:20) at Module._compile (node:internal/modules/cjs/loader:1340:27) at Module._extensions..js (node:internal/modules/cjs/loader:1435:10) at Module.load (node:internal/modules/cjs/loader:1207:32) at Module._load (node:internal/modules/cjs/loader:1023:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12) at node:internal/main/run_main_module:28:49 Node.js v20.11.0
ドキュメントやエラーメッセージの通り、 package.jsonでtype: "module"を指定するか .mjs拡張子を利用する必要がある。 これはCommonJSではなくESモジュールを利用することを明示していることになる。
node.jsの場合はpackage.jsonでtype: "module"を指定する方法がよさそう。