Node.js包构建时生成根目录index.js以适配自定义JS运行时
根目录生成index.js导出dist内容的方案
手动创建根目录index.js
在包的根目录新建index.js,根据模块类型写入对应代码:
CommonJS 模块
module.exports = require('./dist/index.js');
ES 模块
若你的package.json中设置了"type": "module",则使用:
export * from './dist/index.js';
集成到构建流程自动生成
如果希望每次构建后自动生成该文件,可在package.json的scripts中添加生成命令,与构建流程关联:
CommonJS 场景
{ "scripts": { "build": "tsc && npm run generate-index", "generate-index": "echo \"module.exports = require('./dist/index.js');\" > index.js" } }
ES 模块场景
{ "scripts": { "build": "tsc && npm run generate-index", "generate-index": "echo \"export * from './dist/index.js';\" > index.js" } }
执行npm run build时,会先完成TypeScript编译输出到dist目录,再自动生成根目录的index.js。
内容的提问来源于stack exchange,提问作者Kris
相关产品推荐
相关产品推荐

