Keywords: Node.js | ES6 Modules | Import | CommonJS | JavaScript
Abstract: This article provides an in-depth analysis of how to enable and use ES6 import statements in Node.js, addressing common errors such as 'SyntaxError: Unexpected token import'. Based on Q&A data and official documentation, it covers configuration methods for different Node.js versions, including using .mjs file extensions, setting the type field in package.json, and the esm package, with rewritten code examples and comparisons to CommonJS modules, highlighting the benefits and implementation details of modular code.
With the evolution of JavaScript, ECMAScript 6 (ES6) modules have become the standard for code organization, utilizing import and export statements. However, Node.js was originally built on the CommonJS module system, which uses require and module.exports, requiring specific configurations to support ES6 modules. Many developers encounter the 'SyntaxError: Unexpected token import' error when attempting to use ES6 import, often due to incorrect Node.js version or file setup. This guide draws from common issues and official resources to detail the steps for enabling ES6 modules, code implementation, and best practices.
Methods for Enabling ES6 Modules
Node.js has provided experimental support for ES modules since version 9.6, with methods varying by version. For Node.js 13 and above, enabling ES modules is straightforward: either save files with the .mjs extension or add "type": "module" to the nearest package.json file. For Node.js versions 9.6 to 12, use .mjs files and run the command with the --experimental-modules flag. Alternatively, the esm package can be used for broader compatibility.
Configuration for Node.js >= v13
- Use the
.mjsfile extension: for example, rename a file toexample.mjsand run it directly withnode example.mjs. - Or set
"type": "module"inpackage.json: this allows the use of.jsfiles, but ensure file extensions are explicitly specified in imports.
Configuration for Node.js <= v12
- Use
.mjsfiles and runnode --experimental-modules filename.mjs: this enables experimental module support but may display warning messages.
Using the esm Package
Install the esm package via npm: run npm install esm or yarn add esm, then start Node.js with the command node -r esm index.js. You can also add a startup script to the scripts field in package.json, such as "start": "node -r esm index.js", to run via npm start.
Code Examples
The following examples rewrite code based on common scenarios to demonstrate how to define and import ES6 modules. Assume a math library module that exports functions for square and hypotenuse calculations.
// mathLib.js or mathLib.mjs (depending on configuration)
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}Import and use these functions in another file. If using .mjs files or package.json setup, write it as follows:
// main.js or main.mjs
import { square, diag } from './mathLib.js'; // Ensure the extension is correct
console.log(square(5)); // Output: 25
console.log(diag(3, 4)); // Output: 5If using the esm package, the code structure is similar, but no file extension change is needed; simply load the package at runtime.
Comparison with CommonJS Modules
ES6 modules differ significantly from CommonJS modules in syntax and behavior. ES6 modules support static analysis, enabling better tree-shaking optimizations, and loading can be asynchronous, improving performance. In contrast, CommonJS uses synchronous loading, which may cause blocking. Additionally, ES6 modules are inherently in strict mode, whereas CommonJS requires explicit declaration. For interoperability, Node.js allows importing CommonJS modules via import statements, but the reverse may have limitations. For example, when importing a CommonJS module, the module.exports object is provided as the default export, and named exports are inferred through static analysis.
Conclusion
Enabling ES6 import statements in Node.js has become a standard practice, with modern versions simplifying the configuration process. Developers should choose the appropriate method based on their Node.js version and pay attention to file extensions and package settings. Migrating to ES6 modules enhances code maintainability and performance while aligning with web standards. As Node.js evolves, ES module support is expected to become more stable and widespread.