TypeScript导入模块正常但export时报错ts2304找不到名称如何解决
问题根因
ES模块规范中不存在export 标识符 from '模块路径'的语法规则:
- 执行
import ActionButton from './components/atom/ActionButton'时,是将目标模块的默认导出值赋值给当前作用域下的ActionButton变量,符合导入语法规则,因此可以正常执行。 - 直接写
export ActionButton from './components/atom/ActionButton'时,JS/TS引擎会先查找当前作用域下是否存在名为ActionButton的变量,再尝试导出该变量,但你并没有在当前作用域声明/导入这个变量,因此触发Cannot find name 'ActionButton'的报错。
可行解决方案
根据你的导出需求选择对应写法即可:
- 需求1:将目标模块的默认导出,作为当前模块的具名导出ActionButton:
export { default as ActionButton } from './components/atom/ActionButton'
- 需求2:将目标模块的默认导出,作为当前模块的默认导出:
export { default } from './components/atom/ActionButton' // 先导入再导出也可,适合需要二次处理导出内容的场景 import ActionButton from './components/atom/ActionButton' export default ActionButton
- 需求3:先导入到当前作用域使用,再对外导出:
import ActionButton from './components/atom/ActionButton' // 可在此处添加对ActionButton的二次处理逻辑 export { ActionButton }
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

