In the Node.js Cli tools project developed with TypeScript, the output of
tsconfig.json is set to
When importing external dependencies such as
boxen, etc., the latest versions of these packages are pure
ES Module packages, resulting in an error like the following and not available.
Through search queries and analysis, the general solutions are as follows.
1. Change your own project to ESM scheme
If possible, change your project to ESM solution, e.g. change
"module": "CommonJS" in
In practice, however, since there are many differences between the
CommonJS and ESM solutions, the actual code logic may also need a lot of modification to adapt.
2. Keep using the most recent older version of a dependency package that supports the CommonJs scheme
This solution is fine in principle, and many open source libraries do the same. However, there is a potential security issue in that none of these packages can be updated, and if they and their indirect dependencies are exposed to security problems, these security risks cannot be fixed.
3. Using the
await import(...) method
CommonJS scheme supports the use of the
import(...) to dynamically import.
However, since tsc compiles the output as
CommonJS, it actually compiles all dynamic imports as
Based on the above dynamic import scheme, the problem can be solved by simply avoiding tsc compilation. Using the dynamic compilation feature of
eval, you can use the following example method to achieve this.
After testing, a dynamic compilation solution based on
eval solves this kind of problem, for now as a simple interim solution.
Of course, the long-term option that is most in line with the development of community standards is still option 1.