
moment.jsを使用するため、npmでインストール後、jsファイルにてimportで読み込み、コンソールで
node test.js
コマンドを打ち込み実行したのですが、エラーが発生してしまいました。
test.js
import moment from 'moment' const now = moment(new Date()).format('yyyy-MM-dd HH:mm:ss') console.log(now)
エラー内容は以下の通りです
(node:28188) 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) /Users/aaa/Develop/test-js/test.js:1 import moment from 'moment' ^^^^^^ SyntaxError: Cannot use import statement outside a module at Object.compileFunction (node:vm:352:18) at wrapSafe (node:internal/modules/cjs/loader:1031:15) at Module._compile (node:internal/modules/cjs/loader:1065:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:17:47
エラー内容にありました、通り、package.jsonに"type": "module"
を指定してみましたが、エラーを解消することは出来ませんでした。
package.jsonファイルが2つあったため、2つとも追記してみましたが、エラーを解決することは出来ませんでした。
{ "dependencies": { "moment": "^2.29.4", "type": "module" } }
現状のディレクトリ構成は以下のようになっております。(test.jsはnode_modulesディレクトリと同階層に位置しています)


回答2件
あなたの回答
tips
プレビュー