Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tsc should not care and fail with ts files outside of rootDir #9858

Closed
unional opened this issue Jul 21, 2016 · 90 comments
Closed

tsc should not care and fail with ts files outside of rootDir #9858

unional opened this issue Jul 21, 2016 · 90 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@unional
Copy link
Contributor

unional commented Jul 21, 2016

TypeScript: 2.0.0

I have a fixtures folder which contains .ts files. In my tsconfig.json I set rootDir to src which does contain all my source code (including test).

The fixtures files are there for test cases. tsc shouldn't complain their existence and fail the compilation.

@unional
Copy link
Contributor Author

unional commented Jul 21, 2016

To get around, I add "exclude" back to my tsconfig.json

@mhegazy
Copy link
Contributor

mhegazy commented Jul 21, 2016

the rootDir is used to build the output folder structure. all files have to be under rootDir for the compiler to know where to write the output. without this constraint, if there are files that are not under rootDir, the compiler has two options 1. either they will be emitted in a totally unexpected place, or 2. not emitted at all. i would say an error message is much better than a silent failure.

@mhegazy mhegazy added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jul 21, 2016
@mhegazy mhegazy closed this as completed Jul 21, 2016
@unional
Copy link
Contributor Author

unional commented Jul 21, 2016

@mhegazy Thanks for clarification. By name rootDir I took it as the root dir of source code, much like baseURL for browser. Didn't know it is only for output folder structure.

@HillTravis
Copy link

HillTravis commented Sep 27, 2016

Here is my tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": true,
        "noImplicitAny": true,
        "rootDir": "src",
        "outDir": "build"
    },
    "exclude": [
        ".idea",
        "build",
        "node_modules",
        "typings/globals",
        "typings/modules"
    ]
}

My folder structure looks like this:

  • project
    • build
      • node_modules (symlink to ../node_modules)
    • node_modules
    • src

I want my .ts files in the src folder to be compiled and output with the same folder structures to the build folder. I do this so that I can set my document root to the build folder and keep my src out of the doc root. I'm getting error messages about .ts files in the node_modules folder, same error messages as OP. Note above, I have node_modules excluded. Why is tsc complaining about those?

@mhegazy
Copy link
Contributor

mhegazy commented Sep 27, 2016

@HillTravis your issue seems to be the same as #9552.

@HillTravis
Copy link

HillTravis commented Sep 28, 2016

@mhegazy I'm not sure it's the same. Yes, my structure includes a symlink, but anyplace where that symlink exists should be ignored.

In #9552, there is no src folder, meaning the node_modules folder exists in the path that is being built. In my scenario, the root directory that tsc should be looking at is src, which does not contain node_modules. So it shouldn't be looking at that folder at all. On top of that, I have the node_modules folder explicitly excluded via my tsconfig.json. So it should be doubly ignored. I also have the build folder excluded, and that should cover the symlink to node_modules inside it.

Also, in #9552, there was no mention of the error messages or failed compilation.

I should also mention that I'm using TypeScript 1.8.10.

Specifically, the error messages read:

error TS6059: File '/Users/thill/Projects/nrc/client/node_modules/ng2-datetime/src/ng2-datetime/ng2-datetime.module.ts' is not under 'rootDir' '/Users/thill/Projects/nrc/client/src'. 'rootDir' is expected to contain all source files.

error TS6059: File '/Users/thill/Projects/nrc/client/node_modules/ng2-datetime/src/ng2-datetime/ng2-datetime.ts' is not under 'rootDir' '/Users/thill/Projects/nrc/client/src'. 'rootDir' is expected to contain all source files.

error TS6059: File '/Users/thill/Projects/nrc/client/node_modules/ng2-datetime/src/ng2-datetime/timepicker-event-interface.ts' is not under 'rootDir' '/Users/thill/Projects/nrc/client/src'. 'rootDir' is expected to contain all source files.

@mhegazy
Copy link
Contributor

mhegazy commented Sep 28, 2016

@HillTravis you can trust me on this one :) it is our inconsistent handling of symlinks that throws the compiler off. we follow symlinks only for node module resolution, then use that name as the file name; then the we perform a check to make sure all files are under the source directory using the real path, instead of the user specified path. and that is what generates the error.

@HillTravis
Copy link

HillTravis commented Sep 28, 2016

As a test, I tried removing the symlink. Actually, I deleted the whole build folder. Then I ran tsc again, and still saw the error.

During more testing, I tried commenting out the in-code import and uses of that particular node module (ng2-datetime) and the error went away. So it's only when I attempt to import that node module that I see the error, regardless of symlink.

If you look at the source for that package on GitHub, you'll see that the package.json file has the "main" parameter set to "ng2-datetime.js", although the author also published the .ts file with the same name. This seems to be causing the issue. If I create .d.ts files and delete the .ts files, the issue goes away. It compiled with no issues even after adding the symlink back.

So with all respect, I don't see how this issue could be related to the symlink specifically. It seems to just generally cause issues when the author includes the .ts files in the package.

Do you know if there is any workaround for this? The OP above said the worked around it by adding "exclude" back to the tsconfig.json. I already have the directory excluded, but it's still trying to compile it.

@unional
Copy link
Contributor Author

unional commented Sep 28, 2016

Do you know if there is any workaround for this? The OP above said the worked around it by adding "exclude" back to the tsconfig.json. I already have the directory excluded, but it's still trying to compile it.

This may be related to another, but I can't find it right now. When resolving for a type, tsc always try to look it up from node_modules, while it is not there (related to typings).

@rolfen
Copy link

rolfen commented Nov 18, 2016

"tsc should not care and fail with ts files outside of rootDir" I agree.

I cannot understand why typescript would be looking at JS files outside the rootDir, since that's where all the source should be.
Error message says "'rootDir' is expected to contain all source files", then anything outside that directory should not be expected or assumed to be a source file, as far as TS is concerned!

If this is "Working as Intended", then what exactly is the intent or motivation of this behavior? Is there a case where TS would want to compile source files located outside the rootDir?

On the other hand, adding an "include" section in tsconfig solves the problem. When provided with files or directories to include, TS does not go looking at other files outside that.

@iwllyu
Copy link

iwllyu commented Dec 12, 2016

with typescript 1.8.10

I had a node_modules folder in my homedir ~/node_modules. Running tsc from my project dir ~/projects/myProject/ caused typescript to complain about the following files

../../node_modules/aws-sdk/index.d.ts(7,1): error TS1128: Declaration or statement expected.
../../node_modules/aws-sdk/index.d.ts(7,11): error TS1005: ';' expected.
../../node_modules/aws-sdk/index.d.ts(7,24): error TS1005: '{' expected.
../../node_modules/aws-sdk/lib/config.d.ts(1,1): error TS1084: Invalid 'reference' directive syntax.
../../node_modules/aws-sdk/lib/config.d.ts(29,84): error TS1110: Type expected.
../../node_modules/aws-sdk/lib/config.d.ts(36,62): error TS1110: Type expected.
../../node_modules/aws-sdk/lib/config.d.ts(68,133): error TS1110: Type expected.
../../node_modules/aws-sdk/lib/config.d.ts(75,111): error TS1110: Type expected.
../../node_modules/aws-sdk/lib/request.d.ts(1,1): error TS1084: Invalid 'reference' directive syntax.
../../node_modules/aws-sdk/lib/services/glacier.d.ts(1,1): error TS1084: Invalid 'reference' directive syntax.

very confusing - although not sure why I had a node modules folder in my home dir to begin with.

@mhegazy
Copy link
Contributor

mhegazy commented Dec 12, 2016

@iwllyu can you check your project on [email protected] and file a new issue if you are still having trouble.

@iwllyu
Copy link

iwllyu commented Dec 19, 2016

Still have the issue with 2.1.4 although it complains about a different set of files

Using tsc v1.8.10
../../node_modules/aws-sdk/index.d.ts(7,1): error TS1128: Declaration or statement expected.
../../node_modules/aws-sdk/index.d.ts(7,11): error TS1005: ';' expected.
../../node_modules/aws-sdk/index.d.ts(7,24): error TS1005: '{' expected.
../../node_modules/aws-sdk/lib/config.d.ts(27,84): error TS1110: Type expected.
../../node_modules/aws-sdk/lib/config.d.ts(34,62): error TS1110: Type expected.
../../node_modules/aws-sdk/lib/config.d.ts(66,133): error TS1110: Type expected.
../../node_modules/aws-sdk/lib/config.d.ts(73,111): error TS1110: Type expected.
Using tsc v2.1.4
../../node_modules/aws-sdk/lib/config.d.ts(38,37): error TS2304: Cannot find name 'Promise'.
../../node_modules/aws-sdk/lib/request.d.ts(164,16): error TS2304: Cannot find name 'Promise'.
../../node_modules/aws-sdk/lib/s3/managed_upload.d.ts(15,16): error TS2304: Cannot find name 'Promise'.

I'll create a project to isolate the test case

Well I tried with a fresh project and it wasn't happening. Since this is an older project and I already fixed it by removing the extra node_modules folder, I'm not gonna spend any more time trying to recreate it. Thanks for the help!

@idchlife
Copy link

About this case. If all you import are types (like I'm really surfing on this "front-typescript, back-typescript" wave thing) from outside - maybe tsc can distinguish what I'm doing?
I'm sharing just types of my entities from backend - to my frontend application. Output of course without types and imports of those classes (because they are used only for compile time and intellisense).

@bestwestern
Copy link

Had this as well.
Typescript is too constraining for our team - considering flow now.

@idchlife
Copy link

idchlife commented Dec 6, 2017

guys, any resolution on this now? using types from client code inside backend code and otherwise.

what's the best option? copy-paste there and there and modify if I change types?

making one root dir for 2 projects is not an option, since why backend tsconfig.json will have info on jsx and compile into commonjs when I can use es2015

@unional
Copy link
Contributor Author

unional commented Dec 6, 2017

Does baseUrl work for you?

@idchlife
Copy link

idchlife commented Dec 7, 2017

@unional won't changing baseUrl break all of node_modules imports - requiring to write not

import * as request from "superagent";

but

import * as request from "node_modules/superagent/..something";

?

@MicahZoltu
Copy link
Contributor

Bleh, this is really working as intended? I just ran into this, I told typescript that my source was all in a particular folder (via rootDir) and then it proceeded to completely ignore what I told it because I happened to have a single file with a .ts extension sitting outside of that folder.

This really feels like an error, if I tell the compiler where my source is via rootDir, it shouldn't completely disregard that setting and change my output folder structure because it thinks maybe I did something wrong. It should just ignore any files that are not in rootDir. Alternatively, it should hard fail, not continue to emit output that doesn't align with my desired output folder structure at all!


For anyone coming after me, the following will do what you actually want:

{
	"compilerOptions": {
		"outDir": "./output",
		"rootDir": "./source",
	},
	"include": [
		"source"
	]
}

@RyanCavanaugh
Copy link
Member

RyanCavanaugh commented Mar 5, 2018

I told typescript that my source was all in a particular folder (via rootDir)

This is not what rootDir means! rootDir means "Use this folder as the relative basis for computing the paths in outDir". Which files are part of your compilation is a separate question that is answered by files and/or include/exclude

@MicahZoltu
Copy link
Contributor

Even if I accept that, the current behavior is still in error IMO. If I have any TS files outside of the specified directory then rootDir will not be the basis for computing the paths in outDir, meaning the configuration I specified will be completely ignored.

I think hard failing would be much better because the compiler effectively thinks I have given an invalid configuration. Ignoring configuration when it is invalid is (IMO) not the right way to handle this class of failure.

Example error message that would be far more clear (along with hard failure):

TSC found typescript files outside of rootDir and therefore cannot proceed with compilation. Either change rootDir to include all typescript files, or exclude files outside rootDir, or include only files inside rootDir.

Note: A big part of the reason the current behavior of rootDir feels very wrong is precisely because it doesn't make sense to have files outside rootDir. When one asks oneself (or the compiler) what does it mean to compile files outside rootDir the only answer is "it doesn't make sense". Therefore one comes to the natural conclusion that rootDir specifies sourceDir as well.

@unional
Copy link
Contributor Author

unional commented Mar 6, 2018

The evil is in the naming. It really means relativePathBaseDir or something like that.

@rolfen
Copy link

rolfen commented Mar 6, 2018

I have also noticed that include normally means "look here as well" but in this case it means "only look here".
I would be sensible for it to have another name and be mandatory.

@trollkotze
Copy link

IMO this comment should be especially taken into account to confirm that this is indeed a bug and should be re-opened as such:

Note: A big part of the reason the current behavior of rootDir feels very wrong is precisely because it doesn't make sense to have files outside rootDir. When one asks oneself (or the compiler) what does it mean to compile files outside rootDir the only answer is "it doesn't make sense".

Indeed, it does not make sense. "Source files outside rootDir" simply are not source files, no matter their file extension or content. The compiler will never compile them. So why does he complain about their existence? Is he jealous that there are files not under his rule?

@inca
Copy link

inca commented Aug 20, 2018

+100 on this being a bug (a nasty one actually). Consider following directory structure:

- src/
  - module.ts
- test/
  - module.test.ts
- out/
  - module.js

I would like tsc to compile only the src, because I run tests with ts-node. Having rootDir: 'src' will cause compiling error currently. If you mark tests and other stuff that you only intend to execute with ts-node (or even compile separately maybe?) as "excluded", then bad things start to happen (e.g. vscode highlighting becomes broken in tests)

In fact, no combination of rootDir, excluded and all other options satisfies all requirements (exclude tests from compilation while still being able to run them and to work with them).

And I don't really think my use case is unique, so it's worth reconsidering the "work as intended" label at least from UX point of view.

@RyanCavanaugh
Copy link
Member

The src / test / out setup was a key scenario addressed by project references

@aharpervc
Copy link

I found this issue because I was googling why typescript was trying to compile my webpack.config.js file after I set rootDir.

I told typescript that my source was all in a particular folder (via rootDir)

This is not what rootDir means! rootDir means "Use this folder as the relative basis for computing the paths in outDir". Which files are part of your compilation is a separate question that is answered by files and/or include/exclude

This is the answer! The docs for rootDir say

Specifies the root directory of input files

Which I took to mean "input source files". I recommend that @RyanCavanaugh's comment replace the current explanation for this option.

@RyanCavanaugh
Copy link
Member

@sebelga I'd probably consider that a bug - allowing .json from outside rootDir would be OK since TS doesn't copy that to the output folder

@sheetalkamat
Copy link
Member

@sebelga I'd probably consider that a bug - allowing .json from outside rootDir would be OK since TS doesn't copy that to the output folder

Thanks not true.. We have some special rules for emitting .json files... If the file is going to be emitted at same location at itself then and then only it is not emitted. In all cases it is emitted (eg when --outDir is specified, it will be emitted into that folder)

@edsilv
Copy link

edsilv commented Sep 28, 2019

@RyanCavanaugh I have a similar use case to @sebelga where I want to console.log out the version number from package.json at runtime.

@sebelga
Copy link

sebelga commented Oct 1, 2019

So my solution was to change my "rootDir": ".", then I have this includes

"include": [
    "src",
    "typings"
  ]

And as the package.json file is included in the lib (built) folder, that contains a "src" subfolder, I wrote a bash script that runs right after the build to clean up things.

#!/bin/bash

rm lib/package.json
mv $(pwd)/lib/src/* $(pwd)/lib
rm -rf lib/src

It does work, but feels quite hacky to me.

@RyanCavanaugh
Copy link
Member

@sebelga Do you have .ts files in the typings folder? If not, it would be legal to set rootDir to src and skip the script.

@dylang
Copy link

dylang commented Oct 2, 2019

@sebelga Instead of const { version } require('../../package.json') or import { version } from 'package.json'), have you tried doing something like this:

import { sync as loadJsonFileSync } from 'load-json-file';

const { version } = loadJsonFileSync('../../package.json');

TypeScript won't care about it being outside of the rootDir this way.

https://github.com/sindresorhus/load-json-file

If you want to avoid hardcoding all the ../.. you can try this:
https://github.com/sindresorhus/read-pkg-up

@sebelga
Copy link

sebelga commented Oct 7, 2019

@RyanCavanaugh I can't set it to "src" as mentioned above. I am importing "package.json" outside our src (import pkg from '../package.json';) and tsc does not allow that.

Thanks for sharing this @dylang ! I will try it.

@mik-jozef
Copy link

I told typescript that my source was all in a particular folder (via rootDir)

This is not what rootDir means! rootDir means "Use this folder as the relative basis for computing the paths in outDir". Which files are part of your compilation is a separate question that is answered by files and/or include/exclude

@RyanCavanaugh But it is what rootDir should mean, and this is what this issue is about.

@nullquery
Copy link

I'm not that good at maintaining my composure when I see issues that have been open since 2016 that could probably be very fixed without introducing new issues for existing users by introducing a new "compilerOption" to let the compiler know it can ignore the error in a given use case.

For this, I apologize. I can't help it, because I'm relied upon to provide a good service, yet I occasionally encounter issue threads like these. Why is it so difficult for the authors of TypeScript to implement one simple configuration flag?

I don't think it's because the developers are lazy, or because they're unwilling to help. I don't think anyone here is a bad person, except for myself.

It's this conflict, this debate, which has gone on for years over what appears to be the definition of the property "rootDir". And what to do about this issue.

People get thrown into this debate because they believe that they are right. Yes, "rootDir" serves as the base directory for the source code. Yes, the error is valid.

Yet, the underlying issue still persists. My tooling compiles the code perfectly, yet my IDE displays this error on my screen. It's a perversion. I want those red lines gone. My files don't have errors in them. And if they do, I should focus on those rather than being distracted by these non-issues.

All I want is to suppress this error message. I think that's what most of us want. I don't know if there are other cases here and maybe there are people who would like to speak up about that.

Can we please work together and solve this problem? It would make me so happy to see those red lines gone...

@MicahZoltu
Copy link
Contributor

@nullquery If tsc works but your IDE is showing your red squigglies then it means your IDE is not using the same compiler version or configuration as tsc.

@RyanCavanaugh
Copy link
Member

@nullquery file a bug that shows how to reproduce the problem and we will either fix it or tell you what's wrong with your project configuration

@balupton
Copy link

balupton commented Dec 20, 2019

Following on from @sebelga workaround, here is is a variation that is suitable to go inside your npm scripts

tsc --module commonjs --target ESNext --outDir ./edition-esnext --project tsconfig.json && test -d edition-esnext/source && ( mv edition-esnext/source edition-temp && rm -Rf edition-esnext && mv edition-temp edition-esnext ) || true

Example usage here.

Boundation will apply it for you automatically.

@nullquery
Copy link

The solution is Project References.

To use this, edit your "tsconfig.json" file and add this to the end of the file (outside of the "compilerOptions"):

"references": [
	{ "path": "../common" }
]

This will allow you to reference files in the "../common/" folder (and all sub-folders).


My earlier confusion was stemming from the fact that IntelliJ and my untainted gulp-typescript task were giving me different results despite using the same "tsconfig.json" file.

It turns out that for some reason, "gulp-typescript" is trying a best-effort approach to compilation.

An error in TypeScript (such as let z: number = '') will be flagged in IntelliJ but "gulp-typescript" compiles it just fine.
Only JavaScript syntax errors (such as let 1z = '') are flagged by "gulp-typescript".

So, if you're a "gulp-typescript" user, you may experience such an issue depending on your version of "gulp-typescript" and your configuration. (I'm using the latest version at the time of writing, but I'm assuming someone from the future might be reading this. I hope times are better for you.)


I know the use of Project References is buried somewhere in this avalanche of responses, but it would have been better if this were documented better.

The top 3 results for "TS6059" on Google all lead to GitHub issues. It would have been a lot clearer to me if there was a page documenting these common errors and their solutions.

@MicahZoltu Is this something that can be addressed? Should I make a new issue, or is this something that would go faster if it were discussed internally between the main contributors?

@MicahZoltu
Copy link
Contributor

(FWIW I'm not part of the TypeScript team)

Generally, I recommend against using paths unless you absolutely have to. I believe its purpose is to allow for compatibility with legacy JS projects with weird dependency structures but I don't believe its intended to be used on any new projects, and if you find yourself needing it you may want to consider migrating away from it when you have the opportunity. I don't use it personally so I can't really help with issues you may have with it, but I have seen lots of people struggle with it and the solution is usually "stop using it".

As for gulp-typescript, it sounds like perhaps the version of TSC being used by gulp-typescript is different from the version of TSC being used by IntelliJ. When you see symptoms like you describe, that is usually the problem (the other being that they are not using the same tsconfig.json).

@nullquery
Copy link

nullquery commented Dec 31, 2019

The version used by "gulp-typescript" should be identical; both versions are derived from node_modules. I've tried various ways both of catching errors and modifying settings related to it (including messing around with the various "reporters" provided by "gulp-typescript" and attempting to override settings to emit more errors. Nothing seems to work.

It's fine though. As long as IntelliJ gives me errors, I'm happy to accept that the Gulp task will ignore them.


I'm not a fan of overhauling my method in favour of the preferred method of the week. The project structure I have makes sense to me. It keeps everything contained yet gives me the flexibility to split things up into multiple components.

I don't believe in "allowing compatibility for legacy reasons," and especially when it comes to project references. It must be possible to reference files outside of the rootDir or you're simply not going to have the freedom to define the project structure in a way that makes sense to you & your team.


When I first began working with TypeScript, I ran into numerous issues. Among them:

  • For including JavaScript files the go-to solution seemed to be AMD at the time. The website sounded official and there were many examples online of AMD in production use. But apparently, Webpack was the new big thing and so some projects simply didn't work in an AMD environment. Lesson learned: Not everyone is going to adopt the new method, so you're always screwed.

  • The road from TypeScript to the finalized minified JavaScript (with source mappings) was not clear to me. Several different methods were available at the time, but none of them seemed to work natively with "tsconfig.json" files and/or my IDE at the time. Lesson learned: If you want something done right, you've got to do it yourself; don't rely on other people to do the work for you, no matter how well-intentioned they are nobody is perfect and nobody can predict your workspace.

  • There was one custom thing I wanted: a way to convert the content of HTML files to a JavaScript dictionary for inclusion. This should have been my only stumbling block, but in the end, this turned out to be one of the easier scripts to write.

I ended up having to develop my own Gulpfile to handle everything. It does the following:

  • Copies the minified JavaScript files for distribution from node_modules folder to my webroot. It sounds simple, but almost every JavaScript library I tried to include had a different place where they stored their minified JavaScript files. There was no configuration, no clear path to the files. I ended up having to write separate scripts for each JavaScript library I wanted to include. It works, assuming the location doesn't change in future versions, but if it does I can always change the copy script.

  • Compiles TypeScript according to the local "tsconfig.json" file which generates separate files in an output directory (using outDir) so I can be sure that TypeScript is compiled the same way in my IDE as it will be in Gulp (hahahahaha!), then uses the "rollup" plugin to compress those files into a single JavaScript file, then runs UglifyJS to minify this file, all while maintaining a source mapping that maps back to the original TypeScript file.

  • (Custom task) Generates a JavaScript file containing a dictionary called html_templates for each HTML file in the TypeScript source root and places it in my webroot folder as a minified JavaScript file.

There may be more elegant ways out there, but after jumping from one open-source project to the next, I had quite enough of juggling between the solutions each of them was offering.

The approach I've chosen works, it's simple enough to understand (especially now that I understand that "gulp-typescript" does something different) and I'll probably continue using this for years to come.

The best solution is one that you understand yourself. While this doesn't help anybody who tries to help me (which I appreciate very much! the help I mean, not the confusion) I can speak from experience that there will always be something wrong with any solution so it's better to stick with something you own yourself than something that is designed, developed and produced by a multicultural team of various beliefs, sexual orientations and gender identities.


tl;dr please don't break project references. I need that for my tooling to work. thank you

@al6x
Copy link

al6x commented Apr 8, 2020

I gave up setting up multi-project TS setup proerly and just do tsc -w in every project and npm link, and then you can just ignore all the complexities of multi-project tsconfig and just refer to other project like it's plain node.js dependencies in node_modules.

But today in one project I changed target from es5 to es6 and it won't compile anymore because File '.../lib.ts' is not under 'rootDir'.

File structure:

/app
 - tsconfig.json // rootDir = "."
 - app.ts (

/app/node_modules/lib
 - tsconfig.json // rootDir = "."
 - lib.ts
 - lib.js
 - lib.d.ts

Why tsc in /app cares about /app/node_modules/lib/lib.ts file? It shouldn't use that file at all. There's compiled /app/node_modules/lib/lib.js and /app/node_modules/lib/lib.d.ts.

If /app/node_modules/lib/lib.ts deleted - surprise - it compiles fine.

@unional
Copy link
Contributor Author

unional commented Apr 9, 2020

@alexeyPetrushin you can take a look at some of my projects. It seems to be working fine. e.g.:

@SephReed
Copy link

import * as pkg from '../package.json';

NOPE. And there's no way to turn this error off I can find.

@dandv
Copy link
Contributor

dandv commented May 3, 2020

@SephReed: I've spent 200 rep points on StackOverflow and someone contributed this very simple solution for importing ../package.json. All you have to do is place a typings.d.ts file in the same directory as package.json, with this contents:

declare module '*.json';

I have no idea how this works, but honestly, I don't care. At that stage, TS was forking for itself, not for me.

@trulysinclair
Copy link

I surprised this is such a heated debate. But I understand the reasoning. For me, I have of course the source folder, but I also have build scripts outside of that folder that isn't meant to be compiled but definitely include type support, because let's be honest your best IntelliSense is TypeScript.

repo/
⊢ config/  << provide TS support, but don't build this directory
  ⨽ webpack.config.ts 
⊢ scripts/  << provide TS support, but don't build this directory
  ⨽ release.ts
⊢ src/        << build this directory
  ⨽ example.ts
⨽ tsconfig.json

So I use "rootDir": "src" to make sure the files are directed into dist and not dist/src. But of course, TypeScript likes to complain about this setup, but since I use Webpack it doesn't error for me.

@cdpark0530
Copy link

cdpark0530 commented Jun 29, 2020

I finally got what this flag exactly means without several comments that don't make it any clearer. Just cheers with this.

The options that sets folders and files for tsc to take account into compliation: "files", "include", "exclude".

Then what you use "rootDir" for?
rootDir is the root of the directory structure(hierarchy) to your source files, which tsc uses to emit the same directory structure starting from the tsconfig.json directory or "outDir" if it's specified. So this is not the path that tsc uses as the base path for "outDir". "outDir" is just the root that tsc emits output files.
For an instance, let's say your java project has this directory structure.

- src
  - main
    - java
    - resources
      - static
        - js
        - ts
          test.ts

When you set "include" and "rootDir" as down below, tsc will generate the output as:

"include": "src/main/resources/static/ts" *
"rootDir": "." *

- src
  - main
    - java
    - resources
      - static
        - js
        - ts
          test.js *
          test.ts

When you also set "outDir" as down below, tsc will generate the output as:

"include": "src/main/resources/static/ts"
"rootDir": "."
"outDir": "build" *

- build
  - src
    - main
      - resources
        - static
          - ts
            test.js *
- src
  - main
    - java
    - resources
      - static
        - js
        - ts
          test.ts

Probably you wanted to have this by setting "rootDir" option and changing "outDir" option as down below.

"include": "src/main/resources/static/ts"
"rootDir": "src/main/resources/static/ts" *
"outDir": "src/main/resources/static/js" *

- src
  - main
    - java
    - resources
      - static
        - js
          test.js *
        - ts
          test.ts

So when you have set "rootDir" option that doesn't cover the scopes of files except from "exclude" option, tsc fails to build because it doesn't make sense with the purpose of "rootDir" option.

Yeah it's completely a bad naming practice. It should've been just "rootOfStructureOfInputs" or something. And also, "outDir" should've been just "rootOfOutputs".

@MikeMitterer
Copy link

What you see on the SS is not a WebStorm problem - it comes from TS DevServer.
The second recommended import is crap. It picks up from the "communication" source folder. I don't know who the heck should want that. Compiling a file with such an import produces a bunch of problems.

I also tried:

"exclude": ["lib", "node_modules",
        "..", "../..", "../../..", "../../../..", "../../../../..", "../../../../../.."
    ]

Didn't solve the problem either

Bildschirmfoto 2020-07-22 um 10 08 28

@MikeMitterer
Copy link

@mhegazy You labeled this issue with "Working as Intended" but thats not true. As you can see in my screenshot, tsc-server provides files outside of my rootDir (in this case mobiservice/src) as import suggestion. To me this looks like a bug...

@TymofieievVolodymyr
Copy link

Could you please help. with configurations of tsconfig

  • include to compilation files file1.ts and file2.ts from root of project
  • include all typescript files from any directory nested to any level of src, excluding files *.test.ts
  • concatenate and emit output to the file dist/main.js

Tried this option
{
"compilerOptions": {
"target": "es5",
"module": "amd",
"outFile": "./dist/main.js",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
},
"exclude": [
"*.test.ts"
],
"include": [
"file1.ts","file2.ts"
]
}

But unfortunately, include doesn't like rootDir

@MicahZoltu
Copy link
Contributor

@TymofieievVolodymyr For community assistance with TypeScript, I recommend joining the community run TS Discord server: https://discord.gg/BMBfgBGvf7

I suspect someone there will be able to help you out.

@TymofieievVolodymyr
Copy link

@TymofieievVolodymyr For community assistance with TypeScript, I recommend joining the community run TS Discord server: https://discord.gg/BMBfgBGvf7

I suspect someone there will be able to help you out.

Thanks)

@microsoft microsoft locked as resolved and limited conversation to collaborators Jan 4, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests