假设你在进行项目维护时,遇到了一些需要老模块的项目,发现有部分代码用 require 引入模块,而其他部分用 import 引入。
这时候你可能会想,究竟这两者有何区别,什么场景下用哪个更合适呢?
接下来,我们通过一些生活中常见的例子来帮助你理解这些概念。
基本概念
require 是什么?
- Node.js 早期用的模块导入方式。
- 就像去超市买东西,需要什么就拿什么,用的时候才去取。
- 示例代码:
const fs = require('fs'); // 导入文件系统模块 const path = require('path'); // 导入路径处理模块
import 是什么?
- 是现代模块导入的方式。
- 类似于提前下订单,需要什么先声明好。
- 示例代码:
import { ref } from 'vue'; // 导入 Vue 中的 ref 功能 import axios from 'axios'; // 导入网络请求工具
主要区别
1. 加载时机
require:
- 像点外卖,等到需要时才下单获取。
- 运行时才加载模块,更灵活。
if (需要使用模块A) { const moduleA = require('./A'); }
import:
- 像在餐厅预订座位,必须提前说好要什么。
- 编译时就要确定模块,语法更规范。
import moduleA from './A'; // 必须在文件开头声明
2. 使用场景
require 常见于:
- Node.js 服务器开发。
- 维护老项目时。
// 例如:读取配置文件 const config = require('./config.json');
import 常见于:
- 现代前端框架(如 Vue 或 React)。
- 新项目开发时。
// 例如:Vue 组件导入 import HelloWorld from './components/HelloWorld.vue';
3. 实际应用例子
require 示例:
// Node.js 中读取文件内容
const fs = require('fs');
fs.readFile('test.txt', 'utf8', (err, data) => {
console.log(data);
});
import 示例:
// Vue 中的动态导入,实现懒加载
async function loadComponent() {
const UserProfile = await import('./UserProfile.vue');
}
使用建议
-
新项目优先使用 import
- 性能更好。
- 代码更清晰。
- 更容易做优化。
-
特殊情况下使用 require
- 需要动态加载模块。
- 在 Node.js 环境下开发。
- 维护老项目时。
补充说明
import是未来趋势。- 支持树摇(Tree Shaking),减小代码体积。
- 现代浏览器支持
import。 - Node.js 新版本已默认支持
import。