Home > Web Front-end > JS Tutorial > How to Fix the 'Cannot Use Import Statement Outside a Module' Error in Node.js?

How to Fix the 'Cannot Use Import Statement Outside a Module' Error in Node.js?

Patricia Arquette
Release: 2024-12-07 03:33:09
Original
191 people have browsed it

How to Fix the

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"
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template