Unable to use import instead of require, or unable to build dependensides with ts-node & tsdx

1.2k Views Asked by At

I have the following problem and know exactly why it has been triggered, but I haven't found any solution yet, so probably the community may help me with that.

I am using tsdx for initiating ts repos, and also ts-node for quick debug (instead of building code each time).

Recursive Dilemma:

So, each time when I want to add the module to my package via yarn add modulename and if in my tsconfig.json file in compilerOptions option: "module": "commonjs" has the following value, tsdx build unable to build code, and return me the following error:

Error: Incompatible tsconfig option. Module resolves to 'CommonJS'. This is incompatible with rollup, please use 'module: "ES2015"' or 'module: "ESNext"'

module: "ES2015"

BUT!

if I will update compilerOptions to module: "ESNext" from commonjs, ts-node will give me an error, because it's still unable to use import {Method} from Module instead of const x = require(CommonJS) (which is quite old bug, according to this issue and this question) enter image description here

  • Typescript -v 4.1.5 (latest)
  • ts-node: "^9.1.1"
  • node -v: 15+
  "compilerOptions": {
    "module": "commonjs", || "ESNext"
    "lib": ["dom", "esnext"],
    ...//other options

According to that, I am using WebStorm and README.md from ts-node repo, I understand, that I could update Environment Variables with custom tsconfig. So in that case I need two tsconfig files in repo, for ts-node and for production. So the question is: maybe there is another TS_NODE_FLAG, especially for module compiler options? So I could run ts-node with the flag, that would overwrite this minor parameter?

2

There are 2 best solutions below

2
On BEST ANSWER

Currently working compromise is having two config files, which are exactly the same:

  • tsconfig.json
  • tsconfig.dev.json

except that the second has "module":"commonjs"

Compomise

The second option, which actually somehow not working for me is adding to WebStrom's Environment Variables TS_NODE_COMPILER_OPTIONS='{"module":"commonjs"}' from this question.

0
On

another option:

import typescript from 'rollup-plugin-typescript2';
export default {
    ...
    plugins: [
        typescript({
            // 覆盖 tsconfig.json 的配置项
            tsconfigOverride: {
                compilerOptions: {
                    module: "ESNext"
                },
                include: ['src/**/*'],
            },
        })  
    ]
};