ts-node icon indicating copy to clipboard operation
ts-node copied to clipboard

SyntaxError: Cannot use import statement outside a module

Open d1y opened this issue 7 years ago • 44 comments

I use nextjs

import koa from 'koa'
import next from 'next'
import clear from 'clear'
import body from 'koa-bodyparser'
import cors from 'koa-cors'
import logger from 'koa-logger'
import Api from './router'
const dev = process.env.NODE_ENV !== 'production'
const App = next({ dev })
const handle = App.getRequestHandler()
const PORT = parseInt(process.env.NODE_PORT) || 3000

App.prepare().then(() => {
  const Server = new koa()

  Server.use(body())
  Server.use(cors())
  Server.use(logger())

  Server
    .use(Api.routes())
    .use(Api.allowedMethods())

  Server.use(async ctx=> {
    // https://thecodebarbarian.com/building-a-nextjs-app-with-mongodb
    await handle(ctx.req, ctx.res)
    ctx.respond = false
  })

  Server.listen(PORT, () => {
    clear()
    const cowsay = require('cowsay-browser')
    const text = `Koa server listen in ${ PORT }`
    console.log(cowsay.say({ text }))
  })

})

use ts-node server.ts, BTW

➜  next git:(dev) ✗ ts-node server.ts 
/home/d1y/cat/coface/code/next/server.ts:10
import koa from 'koa';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:892:18)
    at Module.m._compile (/usr/node/node-v12.13.0-linux-x64/lib/node_modules/ts-node/src/index.ts:536:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Object.require.extensions.<computed> [as .ts] (/usr/node/node-v12.13.0-linux-x64/lib/node_modules/ts-node/src/index.ts:539:12)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
    at main (/usr/node/node-v12.13.0-linux-x64/lib/node_modules/ts-node/src/bin.ts:212:14)
    at Object.<anonymous> (/usr/node/node-v12.13.0-linux-x64/lib/node_modules/ts-node/src/bin.ts:470:3)
    at Module._compile (internal/modules/cjs/loader.js:956:30)

my tsconfig.json file

{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "es6"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "es2015",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "noImplicitAny": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

Why is this?

d1y avatar Dec 03 '19 02:12 d1y

@blakeembrey

d1y avatar Dec 03 '19 02:12 d1y

You’re trying to execute use it as an ES2015 module, but node.js currently understands CommonJS.

blakeembrey avatar Dec 03 '19 02:12 blakeembrey

Added documentation: https://github.com/TypeStrong/ts-node#syntaxerror.

blakeembrey avatar Dec 03 '19 03:12 blakeembrey

Having the same problem even when using commonjs

	"compilerOptions": {
		/* Basic Options */
		"target": "es2016",
		/* Specify ECMAScript target version: 'ES3' (default),	'ES5',	'ES2015',	'ES2016',	'ES2017',	'ES2018' or 'ESNEXT'. */
		"module": "commonjs",

My project is an expo react-native project, but that shouldn't make a difference.

But the error does seem to come from a dependency:

.../node_modules/expo-constants/build/Constants.js:1
import { AppOwnership, UserInterfaceIdiom, } from './Constants.types';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)

xeruf avatar Jan 07 '20 14:01 xeruf

Update 3: Since Node 13, you can use either the .mjs extension or set "type": "module" in your package.json. You don't need to use the --experimental-modules flag.

Update 2: Since Node 12, you can use either the .mjs extension or set "type": "module" in your package.json. And you need to run node with the --experimental-modules flag.

Update: In Node 9, it is enabled behind a flag, and uses the .mjs extension.

node --experimental-modules my-app.mjs

https://stackoverflow.com/questions/39436322/node-js-syntaxerror-unexpected-token-import?rq=1

Nditah avatar Jan 07 '20 19:01 Nditah

Thanks, I got it fixed that way!

xeruf avatar Jan 09 '20 18:01 xeruf

I had the same problem when I started to used babel... But later, I had a solution... I haven't had the problem anymore so far... Currently, Node v12.14.1, "@babel/node": "^7.8.4", I use babel-node and nodemon to execute (node is fine as well..)

package.json: "start": "nodemon --exec babel-node server.js "debug": "babel-node debug server.js" !!note: server.js is my entry file, you can use yours.

launch.json: When you debug, you also need to config your launch.json file "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/babel-node"

Of course, with babel-node, you also normally need and edit another file, such as babel.config.js/.babelrc file

ghost avatar Feb 13 '20 01:02 ghost

I had the same problem and somehow fixed it. I have written a post about this, hope this helps https://xperimentalhamid.com/how-do-i/fix-cannot-use-import-statement-outside-a-module/

dimahali avatar Mar 03 '20 18:03 dimahali

I had the same problem and somehow fixed it. I have written a post about this, hope this helps https://xperimentalhamid.com/how-do-i/fix-cannot-use-import-statement-outside-a-module/

.mjs extension worked for me, thank you!!

mfahad24 avatar Mar 19 '20 17:03 mfahad24

i keep getting this error when i import react in node for some reason in my project `` import React from 'react' ^^^^^^

SyntaxError: Cannot use import statement outside a module ``

haouarihk avatar Mar 24 '20 20:03 haouarihk

Do u solve this?

kayu0708 avatar Apr 02 '20 06:04 kayu0708

If its an express project make this the last line in your server.js or app.js file module.exports = app; where app is from declared earlier, this this can be any valid variable but here app is used. const app = express();

htolajide avatar Apr 13 '20 16:04 htolajide

To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

nxpatterns avatar Apr 14 '20 20:04 nxpatterns

"type": "module" works, but only works if you are using Node v13.9.0 or above.

davidwoodward avatar Apr 18 '20 22:04 davidwoodward

Add .babelrc to root folder

  • ~/.babelrc
{
  "presets": ["env", "stage-0"]
}

my package.json

  • ~/package.json
"scripts": {
    "watch": "nodemon --exec babel-node src/index.js"
  },
  "dependencies": {
    "dotenv": "^8.2.0",
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-0": "^6.24.1",
    "nodemon": "^2.0.3"
  }

fuadnafiz98 avatar Apr 30 '20 16:04 fuadnafiz98

When using a tsconfig.json, you may override just the module setting like this:

$ npx ts-node -O '{"module":"commonjs"}' my-script.ts

tokland avatar Jul 31 '20 11:07 tokland

In case you stumble upon this and don't want to change the module option to commonjs because this will mess with your tree shaking in webpack. You can have more than one tsconfig.json. ts-loader supports a config entry named configFile. There is also a possibility for extending tsconfig.json files.

In my case I had a vue project and I wanted to test some parts of it with mocha/chai. I created a tsconfig.base.json with the common options. The tsconfig.json file extends the base file and is setup to run with mocha. It's module setting is set to commonjs. Additionally I created a tsconfig.webpack.json extending the base file that has its module config set to es2015 that is provided to configFile in the ts-loader options. I changed no other options anywhere else, so no type: "module" in package.json that was mentioned in this issue since this would interfere with webpack 4.x.

Also as additional info ts-node supports providing a different tsconfig.json via the -P or --project command line option.

Dravere avatar Aug 12 '20 23:08 Dravere

@Dravere we also support overriding compilerOptions inside the same tsconfig, which will only apply to ts-node. So you can keep it all in a single tsconfig file if you want.

{
  "ts-node": {
    // these options are overrides used only by ts-node
    // same as our --compilerOptions flag and our TS_NODE_COMPILER_OPTIONS environment variable
    "compilerOptions": {
      "module": "commonjs"
    }
  },
  "compilerOptions": {
    "module": "esnext"
  }

cspotcode avatar Aug 12 '20 23:08 cspotcode

@cspotcode Oh, that is amazing. Thanks for that hint. Learned a lot about Typescript and ts-node while trying to fix that problem.

Dravere avatar Aug 12 '20 23:08 Dravere

I had the same problem with testing React. I've fixed that by including js files in ts-node:

"transform": { "^.+\\.(ts|tsx|js|jsx)?$": "ts-jest" }

mnajjarian avatar Sep 23 '20 08:09 mnajjarian