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

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)

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 174
  • Comments: 110 (14 by maintainers)

Commits related to this issue

Most upvoted comments

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.

  "compilerOptions": {
    "noEmit": true 
  }

Fixed it for me.

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.

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

"exclude": [
    "node_modules"
  ]

— goes to

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

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

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

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…

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

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.

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

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
  }
}

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: "".

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 😃

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

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

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

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.)

If you want to test another solution and check if it works, here is mine:

Check if these conditions are met for your project:

  1. You have allowJs: true and declaration: true in your tsconfig
  2. You have set package.json main file to the compiled js file (e.g. main: './dist/index.js')
  3. You have imported your root index.ts using relative imports (e.g. import something from '../..') somewhere in your project

Then try changing from

import something from '../..' // Or any other relative import

to

import something from '../../index' // No .ts needed

Hope it helps.

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 🙏

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!

I corrected this by adding an Include section:

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

I also get same problem.

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.

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

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.

Just had the same issue for d.ts files. While everything was set correctly in terms of tsconfig dirs, I had this error because by accident my source code imported from the dist dir rather than src, so it was kinda circular I guess. Changing the import fixed this.

Hope someone will find this comment useful.

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": ["**/*.*"]
}

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.

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.

Using a mono repo? Check for (implicit and unwanted/accidental) cyclic dependencies! That was what caused this issue for me. I wrote an answer here on StackOverlflow

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.

Same problem, I solve It by doing this :

Add in package.json "files": [ "dist/**/*" // Your build repos ]

and add in tsconfig.json

"include": [ "src", "index.ts", // put your files here ],

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.

I needed to manually exclude my build lib/ directory

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.

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.

3. You have imported your root `index.ts` using relative imports (e.g. `import something from '../..'`) somewhere in your project

Then try changing from

import something from '../..' // Or any other relative import

to

import something from '../../index' // No .ts needed

Hope it helps.

@mkermani144 thanks!

@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.

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.

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

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

@Arkanic Deleting the folder is a reasonable workaround, but it has downsides. For example if you have an incremental build, or there’s other expensive steps required to prepare the build folder. It seems like the problem here is that TS doesn’t listen to you when you tell it to exclude something.

If tsc runs fine the first time then errors with this error every time after that it’s because it doesn’t want to overwrite the compiled files. Just delete the folder then run tsc again, and it’ll be fine.

I am dealing with the same issue and the problem is only happening if I have:

"types": "./build/index.d.ts"

in my package.json. Anyone has a clue why that is?

Fixed this by adding "types": "./{name of dist directory}/**/**.d.ts" to my package.json file

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.

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

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

@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!

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.