TypeScript中向对象添加函数属性遇导入函数为undefined问题求助
问题解决方案
以下是几个直接解决Importer属性为undefined的合理方案,不用绕弯子写包装函数:
检查导入语法是否匹配导出方式
如果ethel包中fred是默认导出(比如代码是export default fred),那你当前的命名导入import {fred} from "ethel"就会拿到undefined,得改成默认导入:import fred from "ethel"反过来,如果是命名导出,确认拼写完全一致(大小写敏感,别把
Fred写成fred)。调整代码执行顺序
要是你的查找表数组定义在导入语句之前,比如:const lookupTable = [{SourceType:"Input", DestType: "Output", Importer:fred}]; import {fred} from "ethel";这时候数组初始化时
fred还没被导入,自然是undefined。把导入语句挪到数组定义之前就行:import {fred} from "ethel"; const lookupTable = [{SourceType:"Input", DestType: "Output", Importer:fred}];核实包的导出结构
有些包的导出可能嵌套在对象里,比如ethel实际导出的是export const functions = { fred },那你得先解构出外层对象,再取fred:import { functions } from "ethel"; const lookupTable = [{SourceType:"Input", DestType: "Output", Importer: functions.fred}];排查Tree Shaking导致的函数被移除
如果项目开启了Tree Shaking(比如用Webpack、Rollup),编译器可能误以为fred没被实际使用而把它摇掉,导致值为undefined。可以给导入加保留注释,或者确保函数有实际调用场景:import {fred} from "ethel" /* webpack-preserve */; // 或者在某个地方添加无意义的调用标记,避免被摇掉 if (false) fred();检查模块兼容性
如果ethel是CommonJS模块(用module.exports导出),而你的代码是ES模块,要注意导出形式:- 若
ethel是module.exports = fred,则用默认导入import fred from "ethel"; - 若
ethel是module.exports = { fred },则用命名导入import {fred} from "ethel"。
- 若
内容的提问来源于stack exchange,提问作者SzS
相关产品推荐
相关产品推荐

