代码在这里:https://github.com/timewalker08/wechaty-test/tree/master
根据nodejs文档:
如果最近的父 package.json 缺少“type”字段,或包含“type”:“commonjs”,则 .js 文件将被视为 CommonJS。如果到达卷根并且找不到 package.json,Node.js 将遵循默认值,即没有“type”字段的 package.json。
package.json 中没有“type”字段,因此被视为 CommonJS。
但是,在文件https://github.com/timewalker08/wechaty-test/blob/master/src/wechat-bot.ts中,导入模块时使用的是import而不是require。
为什么?据我所知,CommonJS 中不能使用 import。
TypeScript 将通过将
wechat-bot.js
转换为 import
来生成 require
作为 CommonJS,并且当 type
中没有 package.json
字段时,代码将起作用。
示例代码文件是 TypeScript (.ts) 文件。
tsc
命令将在构建步骤中将其编译为 JavaScript。如果代码有效,生成的 JavaScript (.js) 文件将具有 require
而不是 import
。
生成的 JavaScript 取决于您的
tsconfg.json
,但示例存储库没有 tsconfg.json
文件。
如果
tsconfg.json
文件的 module 为 CommonJS
或 target 为 ES3
或 ES5
,则 TypeScript 会生成 CommonJS 模块,并在生成的 JavaScript 中将 import
语句转换为 require
语句。