javascriptimportrequirecommonjsesmodules

Why import can be used in this commonjs module?


Code is here: https://github.com/timewalker08/wechaty-test/tree/master

According to nodejs document:

If the nearest parent package.json lacks a "type" field, or contains "type": "commonjs", .js files are treated as CommonJS. If the volume root is reached and no package.json is found, Node.js defers to the default, a package.json with no "type" field.

There is no "type" field in package.json, so it is treated as CommonJS.

However, in file https://github.com/timewalker08/wechaty-test/blob/master/src/wechat-bot.ts, import was used to import module instead of require.

Why? As far as I know, import cannot be used in CommonJS.


Solution

  • Short Answer

    TypeScript will generate wechat-bot.js as CommonJS by converting import to require, and the code will work when there is no type field in package.json.

    Explanation

    The example code file is a TypeScript (.ts) file. tsc command will compile it into JavaScript during the build step. If the code works, the generated JavaScript (.js) files have require instead of import.

    Generated JavaScript depends on your tsconfg.json, but the example repo didn't have the tsconfg.json file.

    If the tsconfg.json file has the module as CommonJS or target as ES3 or ES5, then TypeScript generates CommonJS module and converts import statements to require statements in the generated JavaScript.