为何index.js用export default导出报错,换module.exports则正常?
问题原因与解决解析
错误根源:ES模块导出/导入语法不匹配
你在index.js里用的是ES模块的默认导出:
const appReducers = "hello world"; export default appReducers
这种导出方式对应的正确导入语法是不带大括号的默认导入,而你在redux.js里写的import { appReducers } from './reducers/index'是在尝试命名导入——这两种语法完全不匹配。
ES模块里,命名导出需要用export const appReducers = ...的形式,而你只做了默认导出,模块系统找不到对应的命名导出项,自然会抛出export 'appReducers' was not found的错误。
为什么改成module.exports就没问题?
module.exports是CommonJS的导出语法,和ES模块属于两种不同的模块规范。你的项目构建工具(比如Webpack、Babel)在处理ES模块导入CommonJS模块的场景时,会做跨规范兼容处理:
- 当你用
module.exports = appReducers导出值时,构建工具会把这个值同时映射为ES模块的默认导出,并且额外模拟一个同名的命名导出项。 - 这种兼容逻辑让你用ES模块的命名导入语法也能读取到CommonJS的导出值,所以错误消失了。
正确的规范写法(不依赖兼容)
直接遵循ES模块的标准语法,二选一即可:
方案1:默认导出+默认导入
// index.js const appReducers = "hello world"; export default appReducers; // redux.js import appReducers from './reducers/index';
方案2:命名导出+命名导入
// index.js export const appReducers = "hello world"; // redux.js import { appReducers } from './reducers/index';
内容的提问来源于stack exchange,提问作者David Tran
相关产品推荐
相关产品推荐

