0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【エラー対応】Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

Posted at

Next.js と Prisma でscript.ts を実行しようとした時に遭遇したエラーの解決記事

開発環境

$ sw_vers 
ProductName:            macOS
ProductVersion:         13.5.1
BuildVersion:           22G90

$ node -v
v19.2.0

$ npm -v
8.19.3

$ npx next -v
Next.js v13.4.19

$ npx prisma -v
prisma                  : 5.2.0

実行コード

script.ts
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient()

async function main() {
  const dateWithUsers = await prisma.date.findMany({
    include: {
      users: true,
    },
  })
  console.log(JSON.stringify(dateWithUsers, null, 2))
  console.dir(dateWithUsers, { depth: null })
}

main()
  .then(async () => {
    await prisma.$disconnect()
  })
  .catch(async (e) => {
    console.log(e)
    await prisma.$disconnect()
    process.exit(1)
  })

エラー文

$ npx ts-node script.ts

(node:79287) 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/xxx/git/maiamea/practice-next-prisma/script.ts:37
import { PrismaClient } from "@prisma/client";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:74:18)
    at wrapSafe (node:internal/modules/cjs/loader:1141:20)
    at Module._compile (node:internal/modules/cjs/loader:1182:27)
    at Module.m._compile (/Users/xxx/git/maiamea/practice-next-prisma/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Object.require.extensions.<computed> [as .ts] (/Users/xxx/git/maiamea/practice-next-prisma/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Function.Module._load (node:internal/modules/cjs/loader:922:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
    at phase4 (/Users/xxx/git/maiamea/practice-next-prisma/node_modules/ts-node/src/bin.ts:649:14)

原因

tsconfig.json の設定の影響によるもの

解決策

  • script.ts の拡張子を .mts に変更することで回避する
  • ts-nodeの実行オプションに --esm をつける
npx ts-node --esm script.mts
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?