export用于导出模块中的变量、函数或对象。导出的内容可以在其他模块中通过import关键字进行引用。以下是两种不同的export和import的写法:
1. 命名导出和引入
导出:
// 导出单个变量或函数
export const name = 'test';
export function fn() {
console.log('Hi');
}
// 导出多个变量或函数
const age = 18;
const gender = 'male';
const fn1 = function() {
console.log('Hi fn2');
};
export { age, gender, fn1 };
引入:
// 引入单个变量或函数
import { name } from 'js路径';
import { fn } from 'js路径';
// 引入多个变量或函数
import { age, gender, fn1 } from 'js路径'
2. 默认导出和引入
导出:
// 导出一个默认对象
export default {
name: 'test',
age: 18
}
// 导出一个默认函数
export default function() {
console.log('Hi');
}
// 导出一个默认类
export default class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
引入:
// 引入默认对象
import obj from 'js路径';
// 引入默认函数
import fn from 'js路径';
// 引入默认类
import Person from 'js路径';
注意:import引入模块时,需要指定模块路径。在这个路径中可以使用相对路径或绝对路径。