Home >Web Front-end >JS Tutorial >How to Resolve 'SyntaxError: Unexpected Token Import' in Node.js?

How to Resolve 'SyntaxError: Unexpected Token Import' in Node.js?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 22:13:15120browse

How to Resolve

Node.js - SyntaxError: Unexpected Token Import

Importing modules using the "import" syntax is not supported in JavaScript natively. It's a feature introduced with ES6 and is only available in JavaScript environments that specifically enable it.

In the case of Node.js, module loading behavior depends on the Node.js version:

Node.js 13 :

Support for importing modules using "import" is stable and available by default. You can use the ".mjs" file extension or set "type": "module" in your package.json file.

Node.js 12:

Support for importing modules is available behind the "--experimental-modules" flag. You can still use the ".mjs" file extension or set "type": "module" in your package.json file.

Node.js 9:

Support for importing modules is available behind the "--experimental-modules" flag, and requires the use of the ".mjs" file extension.

Pre-Node.js 9:

Importing modules using "import" is not supported. You must use the classic "require" statement to load modules.

Example:

const express = require("express"); // Node.js < 9
import express from "express"; // Node.js 9+

If you encounter the "SyntaxError: Unexpected token import" error, ensure that you are using a Node.js version that supports ES6 imports and that you are using the correct syntax or flags.

The above is the detailed content of How to Resolve 'SyntaxError: Unexpected Token Import' in Node.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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