You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Express启动应用仍用require而非ES6 import?Node9.4.0疑惑解析

Why import express from 'express' Fails in Node.js 9.4.0 & Why Express Docs Use require

Hey there! Let's break down your questions clearly:

1. Why doesn't import express from 'express' work in Node.js 9.4.0?

Node.js 9.4.0 is an older version where ES module support was still in the experimental phase and not enabled by default. Here's the deal:

  • By default, Node.js treats .js files as CommonJS modules (the original module system for Node.js), which uses require() and module.exports.
  • To use ES module syntax like import/export in this version, you had to do one of two things:
    • Rename your file to use the .mjs extension instead of .js
    • Add "type": "module" to your project's package.json file to tell Node.js to treat all .js files in the project as ES modules
  • Without either of these changes, Node.js will throw an error when it encounters import syntax, since it's expecting CommonJS code.

2. Why does the Express official documentation use require() instead of ES6 import?

There are a few key reasons for this:

  • Historical compatibility: Express was released back in 2010, long before ES modules were standardized or widely supported in Node.js. CommonJS was the only module system available at the time, and the docs have retained this syntax to support the huge number of existing projects and developers using older Node.js versions (like your 9.4.0).
  • Lower entry barrier: Using require() means new developers don't have to worry about configuring module systems, file extensions, or Node.js version compatibility just to get started with Express. It keeps the getting-started examples simple and accessible.
  • Ecosystem maturity: For many years, the Node.js tooling ecosystem (build tools, test frameworks, etc.) was built primarily around CommonJS. Sticking with require() in docs avoids confusion for developers who might be using these older tools.

That said, modern versions of Express do fully support ES modules! If you upgrade to a newer Node.js version (v14.13.0 or higher, ideally the latest LTS), you can use import syntax by adding "type": "module" to your package.json or using .mjs files.

内容的提问来源于stack exchange,提问作者bgmaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:29:38