Home >Web Front-end >JS Tutorial >How to Fix the 'Cannot Use Import Statement Outside a Module' Error in Node.js?
SyntaxError: Cannot Use Import Statement Outside a Module
This error occurs when attempting to use ES module syntax outside a module. When the code was written with ES6 module syntax and Babel 7, the latest version of Babel, is used on Node.js 13.2.0 or later, the "Cannot use import statement outside a module" error may be encountered.
To resolve this issue, one of two options can be implemented.
Option 1: Set "type" Field to "module"
In the nearest parent package.json file, add the "type" field with a value of "module". This will indicate that all .js and .mjs files should be interpreted as ES modules. Individual files can be marked as CommonJS by using the .cjs extension.
// package.json { "type": "module" }
Option 2: Explicitly Use .mjs Extension
Alternatively, files can be explicitly named with the .mjs extension. All other files (such as .js) will be treated as CommonJS by default in the absence of a defined "type" field in package.json.
The above is the detailed content of How to Fix the 'Cannot Use Import Statement Outside a Module' Error in Node.js?. For more information, please follow other related articles on the PHP Chinese website!