赞
踩
JavaScript 的模块导出和导入机制,尤其是在使用 ES6 模块语法时。让我们详细解释这个过程,并解决你关于导出和导入的疑问。
导出模块:
export
语法将模块中的变量、函数或对象导出,以便其他文件可以导入和使用这些导出的部分。export
或 export default
语法来导出不同的内容。导入模块:
import
语法可以从另一个模块中导入导出的内容。对于 export default
导出的模块,你可以使用任意名字来导入;对于命名导出(export { ... }
),你必须使用与导出时相同的名字。
- import { createSlice } from "@reduxjs/toolkit";
- import axios from 'axios'
- const channelStore = createSlice({
- name:'channel',
- initialState:{
- channelList:[]
- },
- reducers :{
- setChannels(state,action) {
- state.channelList = action.payload
- }
- }
- })
- const { setChannelList } = channelStore.actions
- const url = 'http://geek.itheima.net/v1_0/channels'
- const fetchChannelList = () => {
- return async (dispatch) => {
- const res = await axios.get(url)
- dispatch(setChannelList(res.data.data.channels))
- }
- }
-
- export { fetchChannelList }
- const channelReducer = channelStore.reducer
- export default channelReducer

- import { configureStore } from '@reduxjs/toolkit'
- import counterReducer from './modules/counterStore'
- import channelReducer from './modules/channelStore'
- export default configureStore({
- reducer: {
- counter:counterReducer,
- channel: channelReducer
- }
- })
export default
和 export { ... }
:
export default
:每个模块只能有一个默认导出(default export
)。你可以导出一个默认的对象、函数或类。导入时,可以使用任意名字来接收这个默认导出的内容。export { ... }
:可以有多个命名导出(named exports
)。在导入时,你必须使用与导出时相同的名字。导出和导入的关系:
export default channelReducer
导出一个默认的 reducer 时,你可以在导入这个模块时使用任意名字,如 import channelReducer from './modules/channelStore'
。export { increment, decrement, addToNum }
,在导入时,你需要使用这些名字来匹配导出的变量名。为什么导入时名字可以随意:
export default
导出的模块,你可以选择任意名称来导入。例如:
- // 在模块文件中
- export default channelReducer;
-
- // 在其他文件中
- import myReducer from './modules/channelStore'; // 可以用任意名字
但对于命名导出,导入时必须使用导出时指定的名字。例如
- // 在模块文件中
- export { increment, decrement, addToNum };
-
- // 在其他文件中
- import { increment, decrement } from './modules/someModule'; // 必须匹配
export default
允许你在导出模块时只导出一个默认对象、函数或类,你可以使用任何名字来导入它。Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。