SyntaxError: Cannot use import statement outside a module
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?
I'm a beginner in NodeJS, and well
After adding "type": "module" I still have this issue, my node version is v14.3.0 and all solutions above didn't work.
and I can't keep using require() because it's not so flexible.
Apparently, nothing happened after adding that:

@danielcnascimento npm run typeorm:migration:run

Thanks @cspotcode , I was using Threads.js that uses ts-node under the hood when it's installed and when I imported a .ts worker, was struggling for hours until adding that ts-node config to tsconfig. Now I can test typescript workers using jest.
Having a similar error where I can't use imports in builds. Not sure how to fix it, tried a few things above and it didnt work.
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node dist/app.js",
"dev": "nodemon src/app.ts",
"build": "tsc -p .",
"migrate": "ts-node ./node_modules/typeorm/cli.js migration:run",
"revert": "ts-node ./node_modules/typeorm/cli.js migration:revert",
"initdb": "dropdb db_dev; createdb -E UTF8 db_dev",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Josh Bedo",
"license": "ISC",
"dependencies": {
"@sendgrid/mail": "^7.4.0",
"@types/express-serve-static-core": "^4.17.16",
"@types/stripe": "^8.0.417",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-graphql": "^0.12.0",
"graphql": "^15.4.0",
"jsonwebtoken": "^8.5.1",
"pg": "^8.5.1",
"reflect-metadata": "^0.1.13",
"stripe": "^8.129.0",
"typeorm": "^0.2.29",
"uuid": "^8.3.2"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/cookie-parser": "^1.4.2",
"@types/cors": "^2.8.6",
"@types/dotenv": "^8.2.0",
"@types/express": "^4.17.9",
"@types/express-graphql": "^0.9.0",
"@types/graphql": "^14.5.0",
"@types/jsonwebtoken": "^8.5.0",
"@types/node": "^14.0.5",
"@types/pg": "^7.14.3",
"@types/uuid": "^8.0.0",
"nodemon": "^2.0.4",
"ts-node": "^8.10.1",
"typescript": "^3.9.3"
}
}
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
example file it throws error on
import Database from "../utils/db";
import Result from "../model/result";
import { hash, compare } from "bcryptjs";
import { v4 as uuidv4 } from "uuid";
import {
Column,
CreateDateColumn,
DeleteDateColumn,
Entity,
Index,
PrimaryGeneratedColumn,
TableExclusion,
UpdateDateColumn,
} from "typeorm";
@Entity("users")
export default class User {
@PrimaryGeneratedColumn()
id: number;
@Index({ unique: true })
@Column({ type: "uuid", unique: true, nullable: false })
ukey: string;
@Index({ unique: true })
@Column({ nullable: false, unique: true })
email: string;
@Column({ name: 'first_name', nullable: false })
firstName: string;
Removing the option "module": "esnext" did the trick for me
Now that we've got top level await as an unflagged feature for Node 14, and TS requires using module: "esnext" to utilize that, this bones anyone trying to use ts-node with that feature.
@shellscape you are setting "module": "esnext", meaning you are asking node to parse and execute import / export syntax, right? Because TypeScript is emitting native import / export syntax?
If so, this requires you to do 2x things: properly configure node to execute your files as native ESM, and use an experimental feature of node: ESM loaders. An ESM loader is the only way that tool such as ts-node can compile in-process when node is executing the file as native ESM.
ts-node documentation is here: #1007
Node documentation is here: https://nodejs.org/api/esm.html#esm_loaders
For those of you simply trying to run a typescript file using ts-node from the command line I got it to work by:
Solution
Changing my tsconfig.json to have this:
"module": "commonjs",
instead of this:
"module": "esnext",
fixed it.
Why
If you want to understand why this fixes it, here's a really good article on what module means and the difference between esnext and commonjs: https://www.tsmean.com/articles/learn-typescript/typescript-module-compiler-option/
Key point: So all in all this can be summarized as: Using TypeScript, node.js and the TypeScript compiler option "module": "esnext" together is next to impossible. So if you're building code that should be ran with node.js, in 2020, you should still choose "module": "commonjs".
When I try importing the paddle it says "Uncaught SyntaxError: Cannot use import statement outside a module" Pls help
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.
C:\parentproject\node_modules\@myprojects\myproject\scripts\validateEnv.ts:2
import fs from 'fs';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.require.extensions.<computed> [as .ts] (C:\parentproject\node_modules\ts-node\src\index.ts:431:14)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js
:72:12)
at Object.<anonymous> (C:\parentproject\node_modules\ts-node\src\bin.ts:157:12)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
Any ideas about what might be going on here?
We'll need to see the postinstall script.
@netpoetica also please move this to our discussion forum since it looks like it's not a bug report or a feature request. Answers given in the discussion forum are more discoverable, meaning it is more likely that the next person with this issue will benefit from the answer as well. This saves work on the whole.
For me setting esModuleInterop to true was the fix.
{
"compilerOptions": {
"esModuleInterop": true
}
}
I have the same problem
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?
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"]
}
@acomito the ts-node key needs to be set on the top-level, not nested in compilerOptions.
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-modulesflag.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-modulesflag.Update: In Node 9, it is enabled behind a flag, and uses the .mjs extension.
node --experimental-modules my-app.mjshttps://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
@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!
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