Home > Web Front-end > JS Tutorial > Why Am I Getting an 'Unexpected Token 'import'' Error in Node.js?

Why Am I Getting an 'Unexpected Token 'import'' Error in Node.js?

Barbara Streisand
Release: 2024-12-12 12:44:12
Original
245 people have browsed it

Why Am I Getting an

Unexpected Token "import" in Node.js

An "Unexpected Token 'import'" error in Node.js indicates that the import syntax is not supported in the current version of Node.js. To resolve this issue, follow the guidelines provided below:

Node.js Versions

  • Node.js 13 :

    • Import can be used with the .mjs file extension or by setting "type": "module" in package.json.
    • The --experimental-modules flag is no longer required.
  • Node.js 12:

    • Import can be used with the .mjs extension or by setting "type": "module" in package.json.
    • The --experimental-modules flag must be used.
  • Node.js 9:

    • Import requires the --experimental-modules flag and uses the .mjs file extension.

Alternatives to Import

Prior to Node.js version 13, import was not supported. Therefore, use the classic require statement to include modules:

const express = require("express");
Copy after login

Babel for ES6/7 Support

If you wish to use ES6/7 features in Node.js, consider using a compiler like Babel. It can transpile your code to be compatible with older versions of Node.js. Consult the Babel documentation for further details.

The above is the detailed content of Why Am I Getting an 'Unexpected Token 'import'' 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