Skip to content

SyntaxError: Cannot use import statement outside a module #922

Description

@d1y

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?

Activity

  1. d1y commented on Dec 3, 2019

    @d1y
    Author
  2. blakeembrey commented on Dec 3, 2019

    @blakeembrey
    Member

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

  3. blakeembrey commented on Dec 3, 2019

    @blakeembrey
    Member
  4. xeruf commented on Jan 7, 2020

    @xeruf

    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)
    
  5. Nditah commented on Jan 7, 2020

    @Nditah

    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

  6. xeruf commented on Jan 9, 2020

    @xeruf

    Thanks, I got it fixed that way!

  7. dimahali commented on Mar 3, 2020

    @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/

  8. mfahad24 commented on Mar 19, 2020

    @mfahad24

    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!!

  9. haouarihk commented on Mar 24, 2020

    @haouarihk

    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
    ``

  10. kayu0708 commented on Apr 2, 2020

    @kayu0708

    Do u solve this?

  11. htolajide commented on Apr 13, 2020

    @htolajide

    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();

  12. nxpatterns commented on Apr 14, 2020

    @nxpatterns

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

  13. 22 remaining items

  14. iltonbarbosa commented on Mar 23, 2021

    @iltonbarbosa

    I am experiencing this error when using a postinstall script in a node_module, I am under the impression that maybe ts-node call in package.json of node_module is picking up the tsconfig.json of the parent rather than it's local one?

    The parent repo has module: es2020 in config because it is an AngularJS project, whereas the child is just a pure CommonJS style project.

    Estou com este mesmo problema no nodejs. Alguém pode me ajudar, por favor?

  15. acomito commented on Jul 26, 2021

    @acomito

    I get

    Unknown compiler option 'ts-node'
    

    When I try this

    {
      "compilerOptions": {
        "module": "esnext",
        "moduleResolution": "node",
        "target": "es2017",
        "outDir": "./dist",
        "lib": ["es6"],
        "types": ["node", "graphql", "express"],
        "typeRoots": ["./node_modules/@types", "./src/@types"],
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true,
        "emitDecoratorMetadata": true,
        "resolveJsonModule": true,
        "pretty": true,
        "sourceMap": true,
        "esModuleInterop": true,
        "isolatedModules": true,
        "allowJs": true,
        "ts-node": {
          "compilerOptions": {
            "module": "commonjs"
          }
        },
      },
      "include": ["src/entities/**/*.ts", "src/**/*.ts", "src/**/*.js", "./index.ts"],
      "exclude": ["node_modules","ormlogs.log", "dist"]
    }
    
    
  16. fspoettel commented on Jul 26, 2021

    @fspoettel

    @acomito the ts-node key needs to be set on the top-level, not nested in compilerOptions.

  17. RahulChouhan96 commented on Sep 4, 2021

    @RahulChouhan96

    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

    How am I supposed to use mjs extension for the ts file? There is typescript-specific code present (like setting type) which is not possible in mjs or in any other file type.

    For eg. I got these two errors
    SyntaxError: Unexpected token ':' and
    Type annotations can only be used in TypeScript files.ts(8010)
    in this code, when I changed extension form ts to mjs

    function run(): void {   // <------- Colon (:) is causing SyntaxError: Unexpected token ':' and
                             //          void is causing error Type annotations can only be used in TypeScript files.ts(8010)
          // Some code
    }

    @Nditah

  18. xiaoshude commented on Sep 6, 2021

    @xiaoshude

    @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"
      }

    this works! thanks a lot!

  19. quizdeveloper commented on Nov 20, 2021

    @quizdeveloper

    I got the same error because I have imported a lib with syntax import ... from and after I change to require() that bug is solved for me. You can see more detail here

  20. added a commit that references this issue on Nov 21, 2021
  21. ialiaslani commented on Dec 18, 2021

    @ialiaslani

    i got the same error because I forgot to set extname in file that I was Importing

  22. leonheess commented on May 6, 2022

    @leonheess
  23. eden-lane commented on Dec 11, 2022

    @eden-lane

    @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.

    when I do this, I get error:

    Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.
    
  24. airtonix commented on Apr 24, 2023

    @airtonix

    This is pretty hilarious:

    😸 hey bro, we got this tool that lets you run typescript on the cli!!!

    🧑‍💻 Amazeballs! proceeds to type standard typescript with imports in a .ts file

    💻 Error you are fail, re-evaluate life choices

    🧑‍💻 🕸️ OMG QQ WTFBBQ, what is this error: ....

    lib author: ./wontfix

    Other Rando on the internet commenting on a typescript tool: hey lol use .mjs 👍🏻 👍🏻 👍🏻 👍🏻

    🧑‍💻 ._. dude, this is typescript.

    Yet Another Rando on the internet commenting on a typescript tool: hey lol add a .babelrc lmao 👍🏻 👍🏻 👍🏻 👍🏻

    🧑‍💻 ./leavesbuilding

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions