在 JavaScript 中,require
和 import
都是用来导入模块的语法,但它们属于不同的模块系统:CommonJS 和 ECMAScript Modules(ESM)。下面是它们之间的主要区别:
require
: 是 CommonJS 的语法,主要用于 Node.js 环境。import
: 是 ES6 (ECMAScript 2015) 引入的标准模块系统,广泛用于现代前端框架(如 React、Vue)和现代浏览器。require
是 运行时同步加载 模块:
const fs = require('fs'); // 同步加载
import
是 编译时异步加载 模块(静态导入):
import fs from 'fs'; // 编译时处理
⚠️ 注意:
import
也可以使用动态导入(import()
)实现异步加载,返回一个 Promise:
import('fs').then(fs => {
// 使用 fs
});
CommonJS | ES Modules |
---|---|
module.exports |
export default |
exports.xxx |
export const xxx |
require() |
import ... from ... |
语法 | Node.js 支持情况 | 浏览器支持情况 |
---|---|---|
require |
默认支持(旧版本) | 不支持(需打包工具) |
import |
需设置 "type": "module" |
支持(现代浏览器) |
math.js
main.js
math.js
内容:// CommonJS
exports.add = (a, b) => a + b;
module.exports = { add };
// ES Module
export const add = (a, b) => a + b;
export default { add };
main.js
对比:require
:const math = require('./math');
console.log(math.add(2, 3));
import
:import { add } from './math';
console.log(add(2, 3));
// 或者导入默认导出
import math from './math';
console.log(math.add(2, 3));
"type": "module"
或使用 .mjs
扩展名。import
,它是未来的标准。require
仍然在很多老项目中使用,尤其是在 Node.js 生态中。特点 | require |
import |
---|---|---|
模块系统 | CommonJS | ES Modules (ES6+) |
加载时机 | 运行时同步 | 编译时(静态) |
是否支持异步 | ❌ 不支持 | ✅ 支持 (import() ) |
默认导出/具名导出 | ✅ 支持(需手动设置) | ✅ 天然支持 |
推荐使用场景 | 老版 Node.js 项目 | 现代前端/Node.js ESM 项目 |
如果你是在写现代项目(如 Vue、React、TypeScript),建议使用 import
;如果是维护旧的 Node.js 项目,则可能继续用 require
。