I have a series of Typescript projects (each an actual compilable target, with its own tsconfig.json). They are sibling directories within one code repository, like this:
myrepo
--/common
--/project1
--/project2
In order to share code between project1
and project2
, I've broken some shared code out into common
. I would like to allow project1
and project2
code to import classes from common
, but not from each other (and common
should not be able to import classes from either of the other two).
Ideally, code in project1
might look like this:
import {CommonClass} from 'common/commonclass';
I have found a way to allow the importing to work correctly, by putting this into the tsconfig.json of project1
:
"baseUrl":".",
"paths":{
"*":["*","../*"]
}
However, I have not yet found a way to limit which of the other subprojects can be the subject of an import
. I've tried using rootDirs
, hoping that it would restrict the allowable source files in the same way rootDir
does, but it actually does not.
How could I whitelist what code is importable in each of my projects? Or is there just some better way of building subprojects in Typescript that I'm not aware of?
You could use multiple tsconfig files to solve some of those problems, but new ones would appear: There's no built-in up-to-date checking, so you end up always running tsc twice.
The tsconfig.json file specifies the root files and the compiler options required to compile the project. JavaScript projects can use a jsconfig.json file instead, which acts almost the same but has some JavaScript-related compiler flags enabled by default.
# References - references Project references are a way to structure your TypeScript programs into smaller pieces. Using Project References can greatly improve build and editor interaction times, enforce logical separation between components, and organize your code in new and improved ways.
I also had to deal with a similar structure and couldn't find an ideal way to do so.
The best I managed to come up with is having a lib
directory in project1
and project2
which contains the compiled common
alongside the definition files.
I used gulp to build the common
project into the different projectX/lib
directories:
gulp.task("common-project1", function () {
var tsProject = ts.createProject("common/tsconfig.json");
return tsProject.src("common/**/*.ts")
.pipe(tsProject())
.pipe(gulp.dest("project1/lib/common"));
});
It's not the best solution because it requires you to run this gulp task every time you change the common
source, but I'v discovered that it doesn't happen very often once that common
is stable enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With