typescripttsconfig

Importing Files in Typescript outside of 'rootDir'


I have a project that has the following file structure

project
|
├── App1/static/App1
|   ├── ts
|   ├── js
|   └── tsconfig.json
|
├── App2/static/App2
|   ├── ts
|   ├── js
|   └── tsconfig.json
|
├── App3/static/App3
|   ├── ts
|   ├── js
|   └── tsconfig.json
|
└── tsconfig.json

Each app needs the compiled Typescript files found in the ts directory to go into each of the js folders found in the same directory. To make this work so far, I have a global tsconfig.json file found at the top of the "project" directory. Then, the tsconfig.json file found inside of each app has the following configuration:

{
    "extends": "../../../tsconfig.json",    // Path to global tsconfig.json
    "compilerOptions": {
        "outDir": "js",                     // Where the transpiled Javascript files go
        "rootDir": "ts",                    // Where the Typescript files are
    },
}

Then, when I run tsc -p App1/static/App1, for example, the Typescript files inside of App1's ts folder get compiled and placed inside of the js folder. Everything okay so far.

Now, my problem is that sometimes App1 needs files from App3, so I do an import similar to this one:

// App1/static/App1/test.ts
import { module } from "../../../../App3/static/App3/ts/module.js"

This works, however, I get the following warning on the import: error TS6059: File 'module.js' is not under 'rootDir' '/ts/'. 'rootDir' is expected to contain all source files.

What changes can I apply to the tsconfig.json file in App1 to make this work. I have tried adding the ../../../App3/static/App3/ts folder as a rootDir in my config (by using rootDirs) but this doesn't seem to work.


Solution

  • Reference each subproject in the package.json file

    // App1 package.json:
    {
        "dependencies": {
            "app2": "../App2/static/App2",
            "app3": "../App3/static/App3",
        }
    }
    

    Now you can reference the other apps as external packages

    import { module } from "app3/js/module.js"

    Import the compiled JavaScript, not source typescript.

    I'm not 100% sure whether you need to fiddle around with import/export settings, but this should get you 90% of the way there.

    You may also need to set "declaration": true in the tsconfig of each subproject, so that .d.ts files are created in the build folders.