如何在TypeScript中实现类似module.exports的导出?Yeoman生成器疑问
在TypeScript中实现Yeoman生成器的正确导出方式
我懂你现在的困惑——用JavaScript写Yeoman生成器时靠module.exports导出类顺风顺水,转成TypeScript就卡壳不知道怎么对应了对吧?别慌,这里有两种靠谱的方式帮你搞定:
方式一:使用TypeScript的默认导出(推荐)
这是最符合TS模块化规范的写法,和你JS里的module.exports效果完全等价,Yeoman能完美识别:
import Base from "yeoman-generator"; import chalk from "chalk"; // 补全你的类型定义 type IFileConfiguration = IComplexFileConfiguration; export default class ServerlessTsGenerator extends Base { initializing() { this.log( chalk.bold( "Welcome to the " + chalk.green("TypeScript for Serverless") + " generator!" ) ); } }
这种写法简洁直观,编译后的代码会自动转换成Node.js支持的CommonJS导出,完全适配Yeoman的加载逻辑。
方式二:直接沿用CommonJS导出写法(兼容旧习惯)
如果你更习惯原来JavaScript里module.exports的写法,TypeScript也支持直接这么写,完全复刻你之前的逻辑:
import Base = require("yeoman-generator"); import chalk from "chalk"; // 补全你的类型定义 type IFileConfiguration = IComplexFileConfiguration; class ServerlessTsGenerator extends Base { initializing() { this.log( chalk.bold( "Welcome to the " + chalk.green("TypeScript for Serverless") + " generator!" ) ); } } module.exports = ServerlessTsGenerator;
这种写法编译后几乎和你原来的JavaScript代码一模一样,兼容性拉满,适合不想改变原有代码结构的情况。
小提示
记得检查你的tsconfig.json,把module字段设置为CommonJS,这样TypeScript编译出来的代码才能被Yeoman正确识别加载哦。
内容的提问来源于stack exchange,提问作者ken
相关产品推荐
相关产品推荐

