Home > OS >  How to properly use ES6 Modules syntax in Typescript files (NextJS)?
How to properly use ES6 Modules syntax in Typescript files (NextJS)?

Time:09-27

The problem seems circular:

  1. package.json does NOT have type: "module". In this case I get this error when using modules in my typescript files:
An error occured while running the seed command:
/Users/me/code/me/prisma-learning/graphql-nextjs/prisma/seed.ts:1
import { PrismaClient } from '@prisma/client';
^^^^^^
  1. So I add type: "module" in package.json and this is now the error:
An error occured while running the seed command:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for 
/Users/me/code/me/prisma-learning/graphql-nextjs/prisma/seed.ts

I just want to use ES6 modules in my TS files. The code is from an official Prisma boilerplate project: https://github.com/prisma/prisma-examples/tree/latest/typescript/graphql-nextjs

CodePudding user response:

It seems that you haven't configured your NextJs project to support typescript:

  1. If you use node seed.ts to run seeder, You need to have ts-node package or compile this file to a regular JS file (using tsc or webpack)
  2. If you use seed.ts file in a page or api of your project, check if you have a tsconfig.json file and typescript is installed as a dev dependency.

If none of them helps, please give more information about your project environments and configurations.

CodePudding user response:

If you look in the package.json for this particual example, you'll see that they have a compiler option specified for ts-node:

    "ts-node": "ts-node --compiler-options \"{\\\"module\\\":\\\"commonjs\\\"}\"",

But for the "seed" command doesn't run it with this option.

So you can just replace:

"prisma": {
    "seed": "ts-node prisma/seed.ts"
  }

with

"prisma": {
    "seed": "npm run ts-node prisma/seed.ts"
  }

and then run npx prisma db seed as documented.

  • Related