RedGiant
RedGiant

Reputation: 4748

Multiple tsconfig.json issue with commonJS for node.js and es6 for reactjs

My current folder structure for typescript:

ts_dev
--client
  *components.tsx
  *tsconfig.json

--server
  *server.ts
  *tsconfig.json
  --share
    *utility.ts

The Node.js server needs to use commonjs modules, and es2015 for the client side components. I place the share folder used by both client and server under the server directory because it needs commonJS for Node.js.

tsconfig.json in server:

{
  "compilerOptions": {
    "module": "commonJS",
    "target": "es2015",
    "moduleResolution": "node",
    "outDir": "../../src",
    "lib": ["es6", "dom"],
    "types": ["reflect-metadata","system"],
    "jsx": "react"
  },
  "exclude": [
    "node_modules",
  ]
}

tsconfig.json in client:

{
  "compilerOptions": {
    "module": "es2015",
    "target": "es2015",
    "moduleResolution": "node",
    "outDir": "../../src",
    "lib": ["es6", "dom"],
    "types": ["reflect-metadata","system"],
    "jsx": "react"
  },
  "exclude": [
    "node_modules",
  ]
}

However I find that the scripts in share are always complied in es6 (Use export,import etc) instead of commonJS, which breaks my server. I suspect it's caused by the tsconfig in the client. What can I do to fix this issue?

Upvotes: 4

Views: 1650

Answers (2)

Aung Kyaw Nyunt
Aung Kyaw Nyunt

Reputation: 481

you already have the separated directory and separated tsconfig file. it means u can generate outDir via from ur separated tsconfig file. or if u want to use one tsconfig.json file and generate es6 and commonjs.
so, try this one.


file structure

Before tsc combile

├── project/
|    └─ tsx
|    |   └─ hello.tsx
|    ├── package.json
|    ├── tsconfig.json
|    └── tsconfig-cjs.json

After tsc combile

├── project/
|    └─ out
|         ├─ es6
|         |   └─ hello.js
|         └─ cjs
|            └─ hello.js
|    └─ tsx
|        └─ hello.tsx
|    ├── package.json
|    ├── tsconfig.json
|    └── tsconfig-cjs.json

code for package.json

"scripts": {
  "tsc": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json"
}

code for tsconfig-cjs.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "./out/cjs"
  },
}

Upvotes: 1

bcr
bcr

Reputation: 2073

I suggest using the include option in each tsconfig.json file with file globs, to limit what files get compiled via each config file.

I solved a similar problem of mine by using different outDirs. What I think is happening to you is that you're compiling the source files twice, and the last time compiles the JS to es2015, overwriting the first. In other words, the server version gets compiled first, then the client version is compiled and overwrites it, because the outputs are going to the same directory.

Upvotes: 1

Related Questions