Languages

Node.js - SyntaxError: Cannot use import statement outside a module

10 points
Asked by:
Hayley-Mooney
677

I have decided to create JavaScript application and run it under Node.js.

I have noticed, import and export keywords don't work. I would like to use pure JavaScript without transpilation.

Should I install some module to Node.js?

Application error:

import { spawn, Thread, Worker } from 'threads';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)   
    at node:internal/main/run_main_module:17:47
1 answer
3 points
Answered by:
Hayley-Mooney
677

To use ES Modules, add "type": "module" property to package.json file.

 

Example package.json file:

{
  "name": "application-name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "type": "module",
  "dependencies": {
    "threads": "^1.7.0"
  }
}

 

See also

  1. Node.js - enable ES Modules (enabling import/export) 
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join