Home > Blockchain >  Cannot Use Import Statement out side a Module
Cannot Use Import Statement out side a Module

Time:12-28

Getting error in import chalk package in my code file. Not sure of the issue.

import chalk from 'chalk';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Node.js v18.12.1

CodePudding user response:

You can only use import in ES modules as per documentation:

import statements are permitted only in ES modules. For similar functionality in CommonJS, see import().

To make Node.js treat your file as an ES module, you need to (Enabling):

To use import, you need to add the following to your package.json:

{
    "type": "module"
}

Node.js has two module systems: CommonJS(Do not support imports) and ECMAScript modules.

Authors can tell Node.js to use the ECMAScript modules loader via the .mjs file extension, the package.json "type" field, or the --input-type flag. Outside of those cases, Node.js will use the CommonJS module loader.

node --input-type=module file.js
  • Related