4
1

More than 1 year has passed since last update.

javascriptで外部モジュールのimportが出来ない

Posted at

エラー1

javacriptで外部モジュールをインポートする記述のあるsample.jsをコンパイルするとSyntaxError: Cannot use import statement outside a moduleというエラーが出ました。

sample.js
import { read, write } from './helper';
$ node sample.js
(node:40624) 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/node/sample.js:1
import { read, write } from './helper';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:353:18)
    at wrapSafe (node:internal/modules/cjs/loader:1040:15)
    at Module._compile (node:internal/modules/cjs/loader:1076:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1166:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Module._load (node:internal/modules/cjs/loader:834:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Node.js v18.4.0

エラーメッセージにES moduleをロードするにはpackage.jsonファイルに"type":"module"を設定するか、拡張子を.mjsにしなさいと書いてあります。拡張子を.mjsにするのは名前に違和感があったのでpackage.jsonを用意しました。

package.json
{
    "type": "module"
}

エラー2

コンパイルし直すと違うエラーがでました。拡張子も付けてないといけないようなので.jsを追加しました。

$ node sample.js read
node:internal/process/esm_loader:91
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/node/helper' imported from /home/node/sample.js
Did you mean to import ../helper.js?
    at new NodeError (node:internal/errors:388:5)
    at finalizeResolution (node:internal/modules/esm/resolve:405:11)
    at moduleResolve (node:internal/modules/esm/resolve:966:10)
    at defaultResolve (node:internal/modules/esm/resolve:1174:11)
    at ESMLoader.resolve (node:internal/modules/esm/loader:605:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:318:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40)
    at link (node:internal/modules/esm/module_job:78:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Node.js v18.4.0
sample.js
- import { read, write } from './helper';
+ import { read, write } from './helper.js';
4
1
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
4
1