Repository navigation
SyntaxError: Cannot use import statement outside a module #922
Description
Activity
You’re trying to execute use it as an ES2015 module, but node.js currently understands CommonJS.
Reacted by bouloan, Sayan Pal, tpedrozo, Mustafa Hayati, Derek Baker, Thomas Lee, David Rodrigues, pixel, Mats Stijlaart, Soichi Takamura and 79 moreReacted by Amirhossein ShakeriReacted by Max, Lara Moshkovich, Omri, Madhav tripathi, Santiago Cendra and hoangtoeicReacted by IcyW, Kirill Leontyev and hoangtoeicAdded documentation: https://github.com/TypeStrong/ts-node#syntaxerror.
Reacted by bouloan, Sayan Pal, Derek Baker, zneix, Gary, munkhuu0324, KA , Taiga Nakayama, kura-yamada, Jay F. Grissom and 9 moreReacted by Daniel Nascimento, Adi Jain, Lee Goddard, Rafael Talero, John Christian Ardosa, wangshangwen, stephen-risk-first, Amy Troschinetz, Siddhu Warrier, Jesse and 13 moreReacted by Marcella, Jay F. Grissom, Anton Kondratev and ChadHaving 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)Reacted by Jimmy Breck-McKye, ⛥ 𝕲𝖍𝖔𝖘𝖙𝖌𝖑𝖎𝖙𝖈𝖍 ☯ ∞Hz, Reyansh, Ali Bey, Mateusz Ziomek, Dmitry Shulga, Benjamin, GuoJunjun, Dwan13, DmitriiBo and 51 moreReacted by Darin Wolyniec, Sanjit Prasad, pawandeep-randhawa, Glavin Wiechert, Nicolas Saudrais, brunosana, Anderson Fernandes and Leo BoraiUpdate 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
Reacted by Minje Park, Reinis Adovičs / kroko, Evan Lesmez, George Campbell, Arthaey Angosii, Dinesh Bogolu, Paul Melero, ᎬᏁᎶᎥᏁᎬᎬᏒ, sheats, Khalil Hakim and 79 moreReacted by Daniel Nascimento, muhammed burak şentürk, Georgi, Cho García, Alcides Bezerra, Witold Milewski, John Christian Ardosa, Albert Marashi, Arthur, George Turkin and 10 moreReacted by Paul Melero, Gerson Calienes, Vieko Franetovic, Zidelmal Yacine, Nabeel, Zhenglai Zhang, Chandra Sekhar Kode, Zach Rosenberger, Ted B, 장재영 and 13 moreReacted by Gerson Calienes, Max Spannring, Elijah Mock, maexwell, Brendan Dolan, Ishan, Albert Peiró, div28, Fabian Brash, Chris Fischer and 13 moreThanks, I got it fixed that way!
Reacted by Rasmus Riis, Ji Nan, Meriemu and TaichiReacted by Max Spannring, Srikanth, Elena Gordillo Viña, ottah and Irtizahussain10I 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/
Reacted by Hamid Ali, Josh Van Riel, weskerhluffy, Devansh Bhushan, Brandon Henry and Wyatt JohnsonReacted by Ali Heydari, zerocewl, Wes Souza, Jens Bodal, Andy Ray, Daniil Demenev, Jeremy Robertson, Garry Belka, Michael Gates, zinc++ and 148 moreReacted by Nikoloz Gabisonia, Valentin Radu, Urie Choi, Mater and Shripad KrishnaReacted by aki, Rasmus Riis and greif.matthiasReacted by 雪人, Mohammed Fahad and Brandon HenryI 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!!
Reacted by Hamid Ali, Brandon Henry and Yuwei JiReacted by Yuwei JiReacted by Brandon Henry and Timoni 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
``Reacted by GUILHERME ALBINO and 1 gal RosemaryDo u solve this?
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();Reacted by thapaliyaprasanga and Gregg B. JensenReacted by Dike GoodluckTo load an ES module, set "type": "module" in the package.json or use the .mjs extension.
22 remaining items
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?
- added 2 commits that reference this issue
on Mar 25, 2021 - added a commit that references this issue
on Apr 9, 2021 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-nodekey needs to be set on the top-level, not nested incompilerOptions.- added a commit that references this issue
on Aug 25, 2021 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
mjsextension for thetsfile? There is typescript-specific code present (like setting type) which is not possible inmjsor 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 formtstomjsfunction 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 }
Reacted by Nikolay Makhonin, Zeno Jiricek and Petra Jaros@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!
Reacted by Thibault, Nelson Castillo, huaycoin, Kalle, Wevelly Felipe, Dénes Harmath, Yves Wang, CC, PC6live, Brian Cooper and 4 moreReacted by Mathieu, Luca and Brian CooperI got the same error because I have imported a lib with syntax
import ... fromand after I change torequire()that bug is solved for me. You can see more detail herei got the same error because I forgot to set extname in file that I was Importing
What if I can't go back to
module: 'commonjs'?Reacted by Marvin Heilemann and Christian Eriksson@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.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:
./wontfixOther 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.babelrclmao 👍🏻 👍🏻 👍🏻 👍🏻🧑💻
./leavesbuildingReacted by Megaache Younes, jorjun, shelby speegle, Steve, Curetix, Zachary Kruse, Niklas, amadeusjposchmann, Ginie, Jaroslav Bereza and 4 more
I use
nextjsuse
ts-node server.ts, BTWmy
tsconfig.jsonfile{ "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?