Typescript: Error "Cannot write file ... because it would overwrite input file."

Created on 8 Mar 2017  ·  99Comments  ·  Source: microsoft/TypeScript

TypeScript Version: 2.2.1

When using Visual Studio 2015 Update 3 I am getting hundreds of errors in the error list like:

Cannot write file 'C:/{{my-project}}/node_modules/buffer-shims/index.js' because it would overwrite input file.

It looks like this all the time. It doesn't actually prevent building, and everything works just fine, but the error list is distracting and difficult to locate "real" errors when they occur.

Visual Studio Error List

My tsconfig.json file

{
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "sourceMap": true,
    "target": "ES5",
    "forceConsistentCasingInFileNames": true,
    "strictNullChecks": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,

    "typeRoots": [],
    "types": [] //Explicitly specify an empty array so that the TS2 @types modules are not acquired since we aren't ready for them yet.
  },
  "exclude": ["node_modules"]
}

How can I get rid of all these errors?

_(I've also posted this question on StackOverflow with no responses yet)_

Needs More Info

Most helpful comment

I found a fix for me. In my case I used outDir and rootDir without specifying files array. When adding the path of outDir to the exclude array everything seems to be working normally.

{
    "compilerOptions": {
        ...,
        "outDir": "./dist",
        "rootDir": "./src",
    },
    "exclude": [
        "node_modules",
        "dist" <-- I had to add this to fix the errors
    ]
}

Maybe TypeScript is watching over the content of the dist folder as well even though it's set as the outDir.

All 99 comments

I also get same problem.

is --allowjs set? can you share the project?

Sorry, I cannot share the project, and no that flag is not set. My tsconfig.json is above, and we just use that with VS2015 Update 3, which just triggers the build with MSBuild normally.

I have teammates complaining about the same issue happening to them on the same projects. I also work on a project at home on a different computer that has the exact same issue & the same setup (TS 2.2.1, VS2015 U3, etc.)

do you see the same behavior if you create a bare-bones project with the same configurations?

We have the same problem https://github.com/wc-catalogue/blaze-elements/issues/299 although with type definitions write access

@Hotell do you see this without "awesome-typescript-loader"? can you share repro steps with me?

yup, as you can see in the issue the output is from running raw tsc second time.

screen shot 2017-03-10 at 5 08 04 pm

just clone the repo https://github.com/wc-catalogue/blaze-elements

  • hit yarn from root
  • hit yarn tsc -> first time compilation ( everything's ok ) => first time definitions/ folder generated
  • hit yarn tsc again -> errors

We're having a similar issue -- same version of typescript (2.2.1) and Visual Studio 2015 (Update 3); the first time the build runs, there are zero errors, but after that we get hundreds of these errors.

It appears that all of the errors (for us) are in the "node_modules" folder, which we have set to exclude in our tsconfig.json file. -- From looking at similar bugs, it seems like the excludes aren't treated the same in this version of typescript?

Our tsconfig.json file:

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "exclude": [
    "node_modules",
    "wwwroot",
    "aot",
    "AngularApp/main-aot.ts"

  ],
  "compileOnSave": true
}

Some of the errors we get (they're all the same, but different files):

Severity    Code    Description Project File    Line    Suppression State
Error   TS5055  Cannot write file 'C:/XYZ/Project.AppWeb/node_modules/zone.js/dist/zone.js' because it would overwrite input file.  TypeScript Virtual Projects     1   Active
Error   TS5055  Cannot write file 'C:/XYZ/Project.AppWeb/node_modules/events/events.js' because it would overwrite input file.  TypeScript Virtual Projects     1   Active
Error   TS5055  Cannot write file 'C:/XYZ/Project.AppWeb/node_modules/core-js/modules/_wks.js' because it would overwrite input file.   TypeScript Virtual Projects     1   Active
Error   TS5055  Cannot write file 'C:/XYZ/Project.AppWeb/node_modules/core-js/modules/_uid.js' because it would overwrite input file.   TypeScript Virtual Projects     1   Active
Error   TS5055  Cannot write file 'C:/XYZ/Project.AppWeb/node_modules/core-js/modules/_to-primitive.js' because it would overwrite input file.  TypeScript Virtual Projects     1   Active

Again, if we delete the "node_modules" folder the build will work once, but then once it's been recreated, it will fail on the next rebuild.

@Hotell i am not seeing this locally, what am i missing?

c:\test\14538\blaze-elements>yarn tsc
yarn tsc v0.18.1
$ "c:\test\14538\blaze-elements\node_modules\.bin\tsc"
Done in 5.46s.

c:\test\14538\blaze-elements>yarn tsc
yarn tsc v0.18.1
$ "c:\test\14538\blaze-elements\node_modules\.bin\tsc"
Done in 5.87s.

c:\test\14538\blaze-elements>dir /B definitions
packages
polyfills.d.ts
styles.d.ts
test-helpers.d.ts
vendors.d.ts

c:\test\14538\blaze-elements>yarn tsc
yarn tsc v0.18.1
$ "c:\test\14538\blaze-elements\node_modules\.bin\tsc"
Done in 4.48s.

@BrainSlugs83 if you have a repro project i would love to take a look.

I am also facing the same problem, these are the errors:
screen shot 2017-03-16 at 23 34 13
And this is my tsconfig.json:
screen shot 2017-03-16 at 23 34 25

Since I am not using typescript at all I just created tsconfig to skip build, I also had to choose target=ES6 otherwise I was having other errors.

is the tsconfig.json part of your project? and can you confirm the content type is "Content"? if so, can you share your project?

@mhegazy Hi, yes I can confirm tsconfig.json is included in the project:

screen shot 2017-03-17 at 19 53 12

But I am sorry I don't know what "content type" are you referring to, can you please clarify?

I can't share the project.

On my project, I can also confirm that the tsconfig file is included in the project file, and it is listed as content.

@max-favilli I think @mhegazy means the "Build Action" when talking about "content type".

Select tsconfig.json in the solution explorer. Bring up the Properties window (F4 key by default). There will be a Build Action property.

Thanks @kevindqc , @mhegazy yes "Build Action" is set to "content"
screen shot 2017-03-18 at 11 21 28

Can you share your virtual project structure with me, to get that you need to:

  • go to Tools > Options > Text Editor > TypeScript > Project, and check Display Virtual Projects when no Solution is loaded;
  • restart VS, and open a file in your project
  • you should now see a new node in your Solution Explorer under the name of TypeScript Virtual Project

@mhegazy like this?

screen shot 2017-03-21 at 02 08 13

Thanks for helping.

I have the same problem. I can't share the project either, but I will try to provide as much information as possible.

I have typescript compilation disabled in the .csproj (<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>)
Instead it is compiled by npm run build:prod, which is in a build event.

The errors are not always there. I have been trying to make them appear (there were shown in VS, so I restarted VS). I've tried building the typescript project, building the solution, running tests, running code analysis, running code coverage, etc. Nothing triggers it. Then, just as I was writing the last sentence, the errors appeared. So it seems to be some background tasks that does it? It seems to happen around 2 minutes after I started a build (at least the 2-3 times I tried it out)

Timeline:
1:37:20 - Opened Visual Studio
1:37:30 - Started solution build
1:38:20 - Build finished
1:39:39 - Errors appeared

I noticed my project was still using the v2.0.3 Microsoft.TypeScript.Compiler and Microsoft.TypeScript.MSBuild nuget packages. I updated them to v2.2.1. So far, no error. Will update if I see the errors again. (Edit: I see the errors again, altough it took a bit longer, ~5 minutes, without me doing anything but building when I opened VS. Actually, I don't even need to build anything to get the error - just opening the project and waiting a few minutes shows the errors)

About those outdated nuget packages, is that normal? I think I got a popup to upgrade my project typescript tools when I installed the new version of typescript, but it seems it only updated <TypeScriptToolsVersion>2.2</TypeScriptToolsVersion>. Should it not also update the nuget packages?

I just updated to Typescript 2.2.1 and having this same issue. Its flagging all the the node_modules but the tsc compiler completes without a problem.

@mhegazy

@Hotell i am not seeing this locally, what am i missing?

right, it was fixed by https://github.com/wc-catalogue/blaze-elements/commit/cdb94bf8feb3a1ad7e21e6fce243e3322c1334cc

sry for delayed answer and thx 4 help!

@Hotell @mhegazy Doesn't seems to work for me.
Maybe it works if you have d.ts files in a "definitions" folder?
But I don't have that. I have @types under "node_modules" which should be inheritedly excluded?

@chrismbarr May I ask if you got this resolved yet? I've been following the thread and even did the fix suggested by @Hotell couple of posts up but I'm still getting these Errors in Visual Studios. They all seem to be coming from the node_modules folder.

Would you be able to enable detailed logging and send us the results? Set the system environment variable TSS_LOG to a value such as -file C:/temp/logs/tsserver.log -level verbose (make sure the logs folder exists). Then after you repro the problem, send/attach the log for analysis. (Note: It may contain data such as file paths and completion lists, so be sure there isn't any data you don't want to share in it).

In my testing I've occasionally seen the project system construct a view of the project that contains the wrong files, causing intermittent errors at unpredictable times. I'd like to see if that may be the cause here.

I can provide my email address if you'd rather send the files direct than upload them (billti at microsoft dot com). Thanks.

@johnlee no, still the same in VS2015. However, I've since started to use Visual Studio 2017 and I have no errors in there!

@billti Variable added, visual studio (2017) restarted, solution rebuilded, but the log file is not being created. What should I check?

Is it definitely a system environment variable (i.e. if you open a new command prompt and run SET TSS is the setting listed)? If not that, is the folder the log is to be written to already present (the logger won't create directories that don't exist). Other than that, its also safer to use forward slashes rather than backslashes in the path.

typescripterrors
:(

@billti Ok, I just checked and the log files are there now. Please find them here attached
tss-log.zip

Thanks. I took a look in that log, and I don't see that error being reported by any calls in it. Did the error definitely occur in the time frame this log covers?

@billti Yes, the errors are occurring at all times:
screen shot 2017-04-11 at 01 25 24

They are just there permanently. And refreshed on every single build.

All of those errors related to incorrect variable declarations (a separate issue we have already fixed for an upcoming release). This issue is about Cannot write file... per the title and screen shots above. Do you not have the Cannot write file... issue?

@billti after posting my previous message (which I left there as a demonstration of my stupidity) I realized the errors are of a different kind. I can only guess the visual studio update I installed few days ago solved the original issue. But I am not sure.
I got rid of these errors from the previous message just removing the types from @types.
Thanks a lot.

@billti I'm trying to have some logs to send you, but none are created. I have set TSS_LOG to -file C:/temp/logs/tsserver.log -level verbose in my system (not user) variables.

C:\temp\logs exists, and I gave full control to Everyone.

If I restart my VS2015, nothing is created inside C:\temp\logs even after I get all my Cannot write file... errors. If I try to type node node_modules\typescript\lib\tsserver.js (and CTRL+C immediately) in a new command prompt, I do get two log files.

Sorry @kevindqc , I didn't realize you were on VS 2015. That logging only applies to VS 2017 (which now uses tsserver.js out of process for the language service).

Going back and looking at your issue - if you are seeing the error list randomly change, I believe that is the same issue @zhengbli just fixed in https://github.com/Microsoft/TypeScript/pull/15080 .

@billti np. I think this issue is only hapenning on VS2015, no? The only user with the problem that was using VS2017 was having different errors related to typings. Someone who switched from VS2015 to VS2017 said the problem went away.

Also, the error list doesn't randomly change - it gets populated at a random time, once, with all those "Cannot write .." errors that this issue is about. Are you sure that #15080 fixes it? I see nothing about this issue except the reference you made to it yesterday? How can I test it? I see there's a 2.3 RC but it was released 9 days ago while the fix was merged 2 days ago :(

Also I noticed the errors stay in my error list even after I close the solution.

Also the person who posted his typescript virtual project was the one with the different errors, so I imagine it wasn't helpful. Here is mine:
image

Is node_modules supposed to be there? It is in my tsconfig excludes. It doesn't contain everything that my physical node_modules folder has though (14 subfolders vs 854 subfolders in my node_modules folder)

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "removeComments": false,
    "sourceMap": true,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es5",
    "baseUrl": "./src",
    "skipLibCheck": true,
    "paths": {
    },
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "dist",
    "typings"
  ],
  "types": [
    "core-js",
    "jasmine",
    "lodash",
    "node",
    "webpack"
  ],
  "awesomeTypescriptLoaderOptions": {
    "forkChecker": true,
    "useWebpackText": true
  }
}

Haven't had the errors so far after upgrading to the TS2.3 tools. Thanks!
Edit: Nop. The errors are still there after all, just took longer to appear.

Seems that this issue related with this issue. Sample solution to reproduce - uploaded.

I found a fix for me. In my case I used outDir and rootDir without specifying files array. When adding the path of outDir to the exclude array everything seems to be working normally.

{
    "compilerOptions": {
        ...,
        "outDir": "./dist",
        "rootDir": "./src",
    },
    "exclude": [
        "node_modules",
        "dist" <-- I had to add this to fix the errors
    ]
}

Maybe TypeScript is watching over the content of the dist folder as well even though it's set as the outDir.

If you have your outDir under your project root, and you are just including everything under the root, then this would be expected. Generally you want to have your build output somewhere other than within the project source folder.

Looks like all the problems above are addressed in this thread or linked issues. Let me know if that's not the case and I'll reopen. Thanks!

@billti I assume that your comment is in response to my previous comment? If so, thanks for clarifying. This makes the matter more obvious to me now as I assumed when specifying the rootDir the compiler will only watch that particular folder and exclude everything else. But the current behavior makes sense.

best solution is from borislemke .
{ "compilerOptions": { ..., "outDir": "./dist", "rootDir": "./src", }, "exclude": [ "node_modules", "dist" <-- I had to add this to fix the errors ] }

I ran into the same issue and found that one of my imports was incorrectly referencing the class in my dist folder E.G
import {ClassName} from "../../dist/ClassName";

As the importing class was in the same folder I changed it to:
import {ClassName} from "./ClassName";

and everything is compiling again :)

We had a pre-defined 'dist' folder in our app. Deleting that fixed it for me.

I think this is the underlaying problem (the last Windows Creators Update):
visual-studio-2015-deletes-file-on-save-cordova-solution

Just add you "dist" folder to the exclusions list in tsconfig.json
ex:
"exclude": ["node_modules", "dist"]

I corrected this by adding an Include section:

"include": [ "*.ts", ], "exclude": [ "node_modules" ]

I ran in to this as well when using an outDir which was under my sources directory.

How is it that the typescript compiler does not know by default that it should not try to compile things in the outDir? That seems strange. Adding the outdir to the exclusion list did fix it though.

i have this problem with netbeans lol 👎

I also got this error when I had two files foo.ts and foo.tsx, both of which would compile to foo.js, obviously.

  "compilerOptions": {
    "noEmit": true 
  }

Fixed it for me.

noEmit is a better solution if you do want to have generated *.js files to be analyzed. They are not necessarily generated with tsc, after all.

In my case, Ream.js generates .ream/**.js which I then import with import XXX from '#out/yyy' in my code (which works, but generates the warning "Cannot write file..." in VS Code).

Basically, the only reason to have "noEmit": false is when you use raw tsc. For all other environments (ts-node/ts-node-dev, webpack, rollup) it's safer to enable it.

Like @uglycoyote what worked for me was to add the outdir to the excludes array. None of the other suggestions worked.

I feel like this issue is related to these:

The issue is happening to me because I set "declaration": true in the tsconfig.json, so it gets angry about the d.ts files in the build folder, even though the directory is outside of the root. I can do a fresh build w/o issues, but any build after that will throw: Cannot write file ... because it would overwrite input file.. From what I could see on the other stories, this used to work in another version, then something must have changed.

Just like I fixed the issues about my test.ts files being outside of the rootDir I had to add the following to the tsconfig.json.

"exclude:" [ "./build" ]

This can also happen with config inheritance. Each config will need to specify outDir separately. It appears that the path in outDir is resolved in absolute terms. Might even be a bug from the user's point of view.

{
  "extends": "../../base/tsconfig.json",
  "compilerOptions": {
    "outDir": "myOutDir"  // <--- Don't forget this
  }
}

Worth checking also if you've an errant reference within package.json to the "outDir"

"main": "lib/index.js",
  "typings": "lib/__types__",      <-------
  "devDependencies": {
    "@types/lodash.mapvalues": "^4.6.4",
    "@types/node": "^10.12.18",
    "@types/winston": "^2.4.4"
  }

I experienced this in a project with project references. None of the excludes mattered, what did was the typings entry hinted at by @elmpp.

So this will produce TS5055: Cannot write file because it would overwrite input file in a project references monorepo:

  "main": "lib/cjs/index.js",
  "module": "lib/esm/index.js",
  "typings": "lib/cjs/index.ts",

but this will report no errors:

  "main": "lib/cjs/index.js",
  "module": "lib/esm/index.js",
  "typings": "src/index.ts",

So evidently I'll either need to manipulate this prepublish, or publish the src in the package.

Setting:

"exclude": [
    "node_modules",
    "dist"
  ]

fixed it for me (my outputDir was dist).

It could be awesome if the output dir is excluded by default for tsc --watch.

For future reference, this happens if you import a module from within itself.

So doing import x from 'mymodule when inside mymodule will trigger this. It's very cryptic, and likely should be fixed!

Similary, I hit the issue if you have an index.ts with a bunch of lines like export * from './foo', and in one of those files, I was importing with import foo from '.' rather than import foo from './foo' in one of those exported files.

I banged my head on this for the last two days until I deleted index.ts and had an import error. It was very non-obvious.

So I think the problem was because I have 2 ts project in the same repo. ( Angular & Nestjs ) , the level 1 folder's tsconfig.json is throwing this error. I fixed by putting exclude "public" , which in public is mine Angular codes with its own tsconfig.json.

I was having this problem because I wasn't sure why ts-node was not working then I tsc to check if the problem was TypeScript. As a result of tsc, I now had dozens of .js files side by side with the ts which I could confirm by running git status

image

The solution was to git clean -f.

In my case, it appears that VS Code had auto imported a file from the dist folder instead of from the src folder. Fixing that solved the problem.

This should really not be closed, typescript should print an error telling you what's going on. It's near impossible to figure out currently. I'm not sure what causes it every so often, VSCode maybe updating tsconfig.json references accidentally, but it slows everything down a ton and each time has been non-trivial to debug.

in Vue project, in the root, this worked for me:

// tsconfig.json
{
    "include": ["./src/**/*"],
    "exclude": ["node_modules", "dist", "public"],
    "compilerOptions": {
      "module": "es2015",
      "outDir": "",
      "moduleResolution": "node",
      "target": "es5",
      "allowJs": true,
      "checkJs": true, // Type checking
    }
}

After i added the
"outDir": "",
problem was gone.

My gole here is just to make ts intellisence work in .js/vue files.

Had the same error message. Issue was that I had two files with the same name but different extension in the same folder so removing the one with .js extension fixed that.

Had the same error message. Issue was that I had two files with the same name but different extension in the same folder so removing the one with .js extension fixed that.

Yeah I had the same issue. I'd renamed a .tsx file .ts that VS-Code helpfully re-created, causing the issue.

Not sure how to put solve this correctly but in my case I just removed "declaration": true from tsconfig.json. D.ts files are not produced, but I do not need them anyway.

To anyone came here by googling a similar error message, let me share my findings:

  1. As you can read, this error was caused because TypeScript compiler was trying to compile a .js file into the same path.
  2. Most likely you don't want compiling .js files at all. If possible, remove allowJs: true from your tsconfig.json or --allow-js from your CLI options.
  3. In case you definitely need them, then you might want to exclude the files that were mentioned in the error message from compilation. Some folks in this thread have done that (maybe without noticing) by adding exclude: ....

    • Be careful not to add 'exclude' under the compilerOptions.

Hope it helps 🙏

I needed to manually exclude my build lib/ directory

There seems to be a bug somewhere which renders some options incompatible. I've found out that using
allowJS true +
rootDir + outDir : OK
rootDir + outFile : NOK : rootDir not taken into account : all files in dir and subdir are set to be compiled and potentially overwritten.
some other option combinations are forbidden.

"allowJs": true
"noEmit": true
work for me.

in Vue project, in the root, this worked for me:

// tsconfig.json
{
    "include": ["./src/**/*"],
    "exclude": ["node_modules", "dist", "public"],
    "compilerOptions": {
      "module": "es2015",
      "outDir": "",
      "moduleResolution": "node",
      "target": "es5",
      "allowJs": true,
      "checkJs": true, // Type checking
    }
}

After i added the
"outDir": "",
problem was gone.

My gole here is just to make ts intellisence work in .js/vue files.

thx, It works for me.

If you are using TS just for type checking ONLY (no compilation) and you need it in .js files, use @guaizi149 solution:

"compilerOptions": {
  "allowJS": true,
  "noEmit": true
}

This will tell TS that it shouldn't worry about compilation, therefore no file will be over written and no warning will be triggered. This is a better solution to using outDir: "".

This can also happen with config inheritance. Each config will need to specify outDir separately. It appears that the path in outDir is resolved in absolute terms. Might even be a bug from the user's point of view.

{
  "extends": "../../base/tsconfig.json",
  "compilerOptions": {
    "outDir": "myOutDir"  // <--- Don't forget this
  }
}

This solution worked like a charm for me! My tsconfig.json looks like this now:

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": "../node_modules",
    "types": ["cypress"],
    "outDir": "myOutDir"
  },
  "include": ["**/*.*"]
}

"allowJs": true
"noEmit": true
work for me.

Thanks @guaizi149 , your solution works for me 👍

Solved - had been including dist directory in my tsc build:

"exclude": [
    "node_modules"
  ]

--- goes to

"exclude": [
    "node_modules",
    "dist"
  ]

Is dist your build folder?

If excluding the outDir didn't work for you, try checking to see if you happen to have duplicate files with the same path and filename but different extensions.

This happens when the declaration files are not excluded from the build. Whenever this occurs, the builder tries to build the existing ".d.ts" files and replace them with the same filename. So that's why you will get the error: Cannot write file ... because it would overwrite input file.

To prevent this, you can exclude your "outDir":"build" in jour tsconfig.json file:

"exclude": [
    "build",
    ....
]

or if you don't have outDir defined exclude all d.ts. extension files:

"exclude": [
    "**/*.d.ts"
    .....
]

Hope this helps

@Abadii: maybe it's because I'm using the -b option while compiling but neither of those approaches worked.

@Abadii: maybe it's because I'm using the -b option while compiling but neither of those approaches worked.

Can you share your tsconfig.json file and what version your tsc is?

@Abadii: Here it is (without the updated exclude obviously). The version of tsc is 3.8.3:

{
    "compilerOptions": {
        "importHelpers": true,
        "target": "es6",
        "module": "CommonJS",
        "lib": ["es2018"],
        "downlevelIteration": true,
        "skipLibCheck": true,
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "experimentalDecorators": true,
        "outDir": "../lib",
        "sourceMap": true,
        "declaration": true
    },
    "exclude": ["node_modules"]
}

@Abadii: Here it is (without the updated exclude obviously). The version of tsc is 3.8.3:

{
    "compilerOptions": {
        "importHelpers": true,
        "target": "es6",
        "module": "CommonJS",
        "lib": ["es2018"],
        "downlevelIteration": true,
        "skipLibCheck": true,
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "experimentalDecorators": true,
        "outDir": "../lib",
        "sourceMap": true,
        "declaration": true
    },
    "exclude": ["node_modules"]
}

Please have a look at the following repo. I've used your tsconfig.json to regenerate the error:

https://github.com/Abadii/tsconfig

P.S. And what will happen when you delete your ../lib folder? Will it build?

@Abadii: It will build if I remove the build folder (actually it will only build if I remove/empty the build folder). This is true even if I exclude declaration files and the build folder.
FYI the project structure is like this:

project\
  lib\
    session.d.ts
    session.js
  src\
    session.ts
    tsconfig.json
  package.json 

and I build with: tsc -p ./src/tsconfig.json
(actually usually I build with rm -rf ./lib && tsc -p src/tsconfig.json but that's what I'm here to fix ;) )

@Abadii: It will build if I remove the build folder (actually it will only build if I remove/empty the build folder). This is true even if I exclude declaration files and the build folder.

So now you know that the build folder is causing the issue. Somehow, your tsc build does not exclude your build folder. You could try to use the absolute path in the exclude.
I've also noted that your build folder is outside your scope ../lib. Maybe thats also the reason why it doesn't exclude. Try ./lib as outDir to check if it changes the behaviour
If you are a windows user, double check that the defined absolute path is correct.

@Abadii: Thanks but I can't use absolute paths since I work on the project on multiple machines and can't guarantee identical folder structure across all of them. To me this seems like a bug - I tell tsconfig to exclude both the folder and declaration files, but it doesn't. Should this be reopened?

@Abadii: Thanks but I can't use absolute paths since I work on the project on multiple machines and can't guarantee identical folder structure across all of them. To me this seems like a bug - I tell tsconfig to exclude both the folder and declaration files, but it doesn't. Should this be reopened?

I see, maybe the last thing you can try is to put your tsconfig file in project/tsconfig.json and change the paths. I'm also out of options if that won't work I guess.

Tried:

  1. Setting outDir -> nope.
  2. Setting allowJs: false -> nope.
  3. Excluding .d.ts -> nope.
  4. noEmit: true -> nope.

I've tried every suggestion in this thread. Not only does the VSCode error persist, but it refers to a file that no longer exists. 🤷‍♂️

Tried:

  1. Setting outDir -> nope.
  2. Setting allowJs: false -> nope.
  3. Excluding .d.ts -> nope.
  4. noEmit: true -> nope.

I've tried every suggestion in this thread. Not only does the VSCode error persist, but it refers to a file that no longer exists.

What happens when you try to build directly trough the terminal?

Set an outDir and be sure to make it empty before building

@Abadii So.... it appears that the reason this was happening was that, even though the JS files were not included, they were failing because they were CommonJS modules.... 🤔 ....

In other words, once everything had proper imports / exports, I stopped getting this issue. So, based on the comments of this thread, and the sheer number of fixes, I think that this is one of those red herring errors. As in, when there's X type of JS / Intellisense / compiling issue, then VSCode throws this Cannot write file error. But, in my case, this was resolved with a solution OTHER than every other of the numerous solutions offered in this thread. 🤷‍♂️ And again, it threw this error on a file that _did not exist_ and _would not be replaced_. So maybe errors are caching, and an unknown error throws a cached error? Something like that? I think someone needs to inspect the code around this particular error.

Commenting here because it is the first thing that came up in my google search.

I ran into this issue too. It seems like some part of the compilation process isn't recognizing that it is inside an excluded directory.

I don't don't see the problem if I do this:

  "exclude": ["**/*.d.ts", "dist", "node_modules"]

I do see the problem if I do this:

  "exclude": ["dist/**/*.d.ts", "dist", "node_modules"]

or this:

  "exclude": ["**/dist/**/*.d.ts", "dist", "node_modules"]

The error occurs despite the fact that the files it is complaining about are clearly inside dist:

error TS5055: Cannot write file '/Users/leila/dev/wip/jest-fp-ts/dist/index.d.ts' because it would overwrite input file.
error TS5055: Cannot write file '/Users/leila/dev/wip/jest-fp-ts/dist/matchers/index.d.ts' because it would overwrite input file.

In my case I have imports set up where src/index.ts imports and re-exports from src/matchers/index.ts which in turn imports and re-exports from src/matchers/eitherMatchers/index.ts.

The first two files are the ones causing the compilation errors. The third file is fine. So it looks like it might be related to how the import / export tree is affecting compilation.

I just stumbled across this issue while having the same problem, and thought I'd add what mine turned out to be in case other people stumble across it the same way.

In my case, I have a monorepo with a separate tsconfig file for each package, that all extend from a base tsconfig. Each packages config has references entries that point to the path of the packages it depends on. I also have a tsconfig.json in the root of the repo that includes files: [] and has references to all of the package directories. This way I can run tsc -b --watch from the root and have it rebuild on changes throughout the entire project.

This worked fine for quite a while, then abruptly started throwing this error even though none of the configs had changed.

I finally tracked it down by attempting to build the one package that was being reported in the error by itself, rather than building the whole project.

Turns out the problem was that I had attempted to have the project import itself. The package name was @my-project/utils, and it worked fine until I moved some code from another package into a file in the utils package. That code included import stuff from '@my-project/utils'; and that was what caused the error. By changing to to import stuff from '.'; instead the error went away..

@jasonk This probably is just revealing my ignorance but wouldn't that only work if your monorepo is being bundled together by something that will resolve all those imports (e.g. webpack)? If your monorepo is composed of modules that can be published and used independently changing to relative imports would cause errors no?

@Ghirigoro No, the problem wasn't that I was using a package path, it's that it was using a package path to import a package from within itself. Even without Typescript, that won't work.

Basically what I had done was the equivalent of this:

$ mkdir problem
$ cd problem
$ npm init -y
$ echo 'console.log( "WORKED!" );' > index.js
$ echo 'require( "problem" );' > test.js

If you then try to run that with node:

$ node ./test.js
internal/modules/cjs/loader.js:985
  throw err;
  ^

Error: Cannot find module '/Users/jasonk/problem/test.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:982:15)
    at Function.Module._load (internal/modules/cjs/loader.js:864:27)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

If you replace the package name then it works correctly:

$ echo 'require( "." );' > test.js
$ node ./test.js
WORKED!

I suspect that what happened was that when the build was run, all of the other packages that were importing from @my-project/utils had that import resolved to packages/utils (because they had the correct entries in the references array in tsconfig), so they built normally. But because that package wasn't supposed to be importing itself that import got resolved to node_modules/@my-project/utils, which was a symlink to packages/utils, but TypeScript didn't detect that they were actually the same project so it tried to build it twice, but since both builds had the same output directory I ended up with this error.

This happens when the declaration files are not excluded from the build. Whenever this occurs, the builder tries to build the existing ".d.ts" files and replace them with the same filename. So that's why you will get the error: Cannot write file ... because it would overwrite input file.

To prevent this, you can exclude your "outDir":"build" in jour tsconfig.json file:

"exclude": [
    "build",
    ....
]

or if you don't have outDir defined exclude all d.ts. extension files:

"exclude": [
    "**/*.d.ts"
    .....
]

Hope this helps

Excluding my build dir solved the issue for me

Most likely, this happens when you try to run one project with two nodes.
For this hypothesis, you can test the count of processes on your computer named "node" after run build.
What I did to solve the problem:
Step 1.
Compare
node -v
and
nvm -ls, the version in use.
In terminal set current node version:
nvm use {neededVersion}
In principle, delete unnecessary versions of the node in nvm (this will help your IDE to automatically determine the normal version of the node).
Step 2.
Determine the current node in your IDE. i.e. in WebStorm:
Preferencies->Languages & Frameworks -> Node.js and NPM: Node interpreter - set needed version.
(In addition, you can check the version of the node for each item everywhere (Typescript))

Also, this problem can occur if the npm packages or git submodules used their own node inside

I was facing this issue for Webdriver IO / WDIO project. It got resolved when I removed the "wdio.config.js" from "include" in tsconfig.json.

Was this page helpful?
0 / 5 - 0 ratings