'Typescript error "Cannot write file ... because it would overwrite input file."

In my Typescript 2.2.1 project in 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

Here is 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?



Solution 1:[1]

It seems like this issue was fixed for me by updating to Typescript 2.3.x

Also, using Visual Studio 2017 was a big improvement as well. I highly recommend that you make both of these updates though.

Solution 2:[2]

In my instance, I was using the outDir option but not excluding the destination directory from the inputs:

// Bad
{
    "compileOnSave": true,
    "compilerOptions": {
        "outDir": "./built",
        "allowJs": true,
        "target": "es5",
        "allowUnreachableCode": false,
        "noImplicitReturns": true,
        "noImplicitAny": true,
        "typeRoots": [ "./typings" ],
        "outFile": "./built/combined.js"
    },
    "include": [
        "./**/*"
    ],
    "exclude": [
        "./plugins/**/*",
        "./typings/**/*"
    ]
}

All we have to do is exclude the files in the outDir:

// Good
{
    "compileOnSave": true,
    "compilerOptions": {
        "outDir": "./built",
        "allowJs": true,
        "target": "es5",
        "allowUnreachableCode": false,
        "noImplicitReturns": true,
        "noImplicitAny": true,
        "typeRoots": [ "./typings" ],
        "outFile": "./built/combined.js"
    },
    "include": [
        "./**/*"
    ],
    "exclude": [
        "./plugins/**/*",
        "./typings/**/*",
        "./built/**/*" // This is what fixed it!
    ]
}

Solution 3:[3]

I got the same issue. In my case, it was the result of the option: allowJs: true.

So I basically had to remove that line to get rid of the errors. I do not see it in your code, but perhaps it helps you here.

Good luck!

Solution 4:[4]

I have run into this issue due to VSCode autocompleting a file in the dist/ folder.

import { SomeClass } from '../../dist/xxx/someclass' 

To solve the problem just fix the import:

import { SomeClass } from './someclass' 

Solution 5:[5]

There's several possible causes to this.

  • In your tsconfig.json:
    • Set outDir to "dist" or the name of another same-level folder. (prefixing with './' is unnecessary). This is where the build files go.
    • Set allowJs to false or delete the line. Note: enabled, allowJs will conflict with the declaration setting/flag. It isn't enabled by default.
    • Include "dist" (or your build folder) in exclude.
  • In your package.json:
    • Set main to "index" or some other chosen name. Don't prefix with the build folder (eg "dist/index"), nor the unnecessary "./".
    • Set types (modern alias of typings) to "index". Adding the extensions (.d.ts or .js) is unnecessary.

Though you can have it a million different ways, for the sake of simplicity and developing understanding it's best to stick to common practices at first - like using "dist", simple tsconfig.json and package.json files at the same level in the tree, and so on. Of course, rooting through the files of your node_modules would also deepen your grasp, but there are more rewarding things in life.

Solution 6:[6]

Adding 'dist' to the excluded directories in tsconfig.json worked for me:

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

Solution 7:[7]

TL;DR: Using mono repo? Check for cyclic dependency!

You might have accidentally imported a type from a package that depends on this package.

I too got this error and none of the other answers helped me. It took a while to pinpoint it, but after at least one hour wasted it turns out the underlying error was cyclic dependency between my packages in my mono repo.

So we use yarn workspaces and have a mono repo structure very similar to Zilliqas (our repo is not open source yet so can't link to it).

Inside package A I had accidentally (don't know how...) imported a type from package B, but package B is in turn dependent on package A - which I've explicitly stated in packages/packageB/package.json:

"dependencies": {
    ...,
    "@mycompany/packageA": "^0.0.0",
    ...
}

This is correct an well. But unfortunately it is possible to accidently import a type from package B in my case in packages/packageA/_types.ts but since I had NOT explicitly stated (because the dependency was implicit, unwanted and accidental) this dependency in packages/packageA/package.json under "dependencies" the typescript compiler (tsc) did not detect the dependency cycle but still fail to build...

So yeah, thanks TypeScript for the awesome error message... such wow, many red herring.

Solution 8:[8]

Set outDir.

"outDir": "./",

this hint is that if you don't set outDir, then the output will be placed directly next to the input file. After allowJs, the JavaScript file will also be compiled. Then, the compiled JavaScript file will overwrite your source file. It’s just reminding you of this.

Solution 9:[9]

None of the answers worked for me so I'll share things that can cause this issue:

  1. You should add the outDir (or at least the declarationDir) to exclude.
"exclude": ["node_modules", "types"]
  1. If your rootDir contains any .js code without specifying an outDir then it will try to compile and override the original javascript, in which case you can specify an outDir.
"outDir": "lib"
  1. This is really the "gotcha" one... If you import anything from anywhere typescript will compile, check and generate type declarations for it. It doesn't matter what's inside your include or exclude, it also doesn't matter what your rootDir is set to, if you import something it will be used, typed, overwritten and output and none of your previous configuration for it will be respected.

For example if you have:

- /src
- tsconfig.json
- randomJsFile.js

With:

"rootDir": "src"

And:

"include": ["src/**/*.ts"]

Then you import that randomJSfile.js anywhere in any /src file, it will generate a *.d.ts file right next to that file (it won't even output it to your types directory) and it will try override that file.

In short this means you should be careful about what you import and not import anything outside of your rootDir into your project (except for node_modules).

This is the one that got me trying to import config from ../webpack.config.js made *.d.ts types generate for webpack (not even in the types directory, just there randomly in place not respecting the tsconfig at all) and it will also try override the imported file and break. Kept on wondering why completely random webpack types started showing up in my directory when I imported the config.

This is even more fun if you have incremental builds enabled and it only breaks some of the time (or if you delete those types and they seem to stay gone (for now)).

Solution 10:[10]

Adding "outDir": "./dist" to compilerOptions in tsconfig.json worked for me when I got this error. I'm pretty sure this is only the Visual Studio Code TypeScript extension outputting this error. I use the ts-loader with Webpack and not the tsc compiler directly so I didn't have to specify the outDir because the webpack config controls that but if this makes the VS Code extension happy it's good.

Solution 11:[11]

In my case it was because i accidentally included a class from dist directory :

import {Entities} from "../../dist";

Just removed this line and everything is fine now.

Solution 12:[12]

Probably the root of the problem is 2 files generating the same module. So if one have two files in the same folder with the same name but with different extensions leads to this error.

eg:

\index.ts
\index.tsx

Solution is changing one of these files names to something else.

Solution 13:[13]

I encounter the error too: Cannot write file 'xx\xxx.js' because it would overwrite input file.

I find out these:

If outDir not specified, .js files will be emitted in the same directory as the .ts files they were generated from.

To avoid overwrite source file unexpectedly, the compiler will show this error.

You need to either specify outDir, or set noEmit: true to avoid emit compiler output files like JavaScript source code.

Solution 14:[14]

Because the problem can have a wide set of reasons! I'm going to share my experience on when i encountered the error !

A story

In my case! I had two files ! One src/index.ts the other on src/test/logToFile.directTest.ts.

excluding src/test/logToFile.directTest.ts solved the problem! It seems each resolution was trying to write to the same file!

My config for the declaration was:

{
  "compilerOptions": {
    "declaration": true,
    "declarationDir": "./dist",
    "module": "commonjs",
    "noImplicitAny": true,
    "lib": ["ESNext", "DOM"],
    "outDir": "./dist",
    "target": "es6",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

And everything was setup correctly! You can notice that i excluded the dist directory. And correctly set the outDir which are necessary (you can get the error if you don't! And all the other answer mentioned that).

More then that i was using the config with other repositories and packages! And i haven't any problems!

At the end ! it was this:

import { Logger } from '../..';

My import was wrong!

It should have been:

import { Logger } from '..';

Porting the module to it's own repository i forget to change the import!

And i included back the file! And tested and all worked well!

And to bring the benefit from the story!

If All the making sense solutions (or things to do) are respected and you still get the problem! Make sure to check your imports within the ts files!

An import can refer to root (for example) and automatically redirect back to dist! And so the .d.ts file! Typescript should normally throw an error! As that stand out of the directory folder! But it didn't! And made that error!

And to bring more benefit

Explaining the error

In short it's described here:

https://github.com/microsoft/TypeScript/issues/6046#issuecomment-210186647

in short an input file is either a file that you pass on the command line, or that is a dependent of one of the files you pass on the command line transitively.

If two maps to the same declaration file! And that can happen when they share the same name! Or refer back to the declaration file itself! Imported from a file! Through a bad import (like in my case)! Or that dist is not ignored!

Looking for imports is a thing to check! If you excluded the dist directory and set up the outDir correctly

Very interesting to know you can check the inputs files through this command:

tsc --listFiles

When the problem reside you'll find the declaration file within the list!

Solution 15:[15]

I had the same issue. In my case it was caused, because I had two files with the same name in one module: index.ts index.tsx.

I renamed one of them and the problem got fixed.

Solution 16:[16]

I faced the same issue, i tried above solution. None worked for me. Then deleting build folder in my case - lib and rerun build cmd worked for me.

Solution 17:[17]

I had the same issue and it's because of the exclude option. If you specify exclude option, you have to add the output directory also.

I had the exclude option like this "exclude": ["resources/js/**/*", "node_modules"] and the output directory set as outDir:"./build".

Adding build to the exclude option fixed the issue.

exclude:["resources/js/**/*", "node_modules", "build"]

Solution 18:[18]

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 | Typescript: Node interpreter - set needed version.

Solution 19:[19]

Use tsc --build --explainFiles to track down how your .d.ts is being included in your build!

e.g.

dist/index.d.ts
  Imported via '..' from file 'mocks/mock-requests.ts'

In this case I should import something other than '..'...

See https://www.typescriptlang.org/tsconfig#explainFiles

Solution 20:[20]

I solved this by removing "declaration": true from my tsconfig.json file. Though now I don't have declarations anymore so that didn't help.

Solution 21:[21]

In my case, I just changed "module": "commonjs" to "module": "esnext" and it fixed it.

Solution 22:[22]

When you are in a lerna package project or a monorepo project, it may work :


fist, your project look like this

packages\
  core\
    tsconfig.json
    package.json 
  common\
    tsconfig.json
    package.json
  tsconfig.base.json

your package.json

  ...
  "main": "./lib/index.js",
  "types": "./lib/index.d.ts",
  "files": [
    "lib"
  ],
  ...

your tsconfig.json

{
  "extends": "../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./lib",
  },
}

You will find that no matter how you change the tsconfig.json file, it doesn't work


So, this is my solution

delete you outDir:"lib" first, or use command rd lib /s /q , and run tsc, it will work

Solution 23:[23]

If you are working within a large code or monorepo sometimes just restarting your editor will suffice or if you are using vscode restarting the typescript language server.

Solution 24:[24]

The allowJs option from another answer here got me thinking that perhaps my configuration didn't allow JavaScript files in the project.

So instead of doing all the outDir stuff that people recommend here, I renamed the problematic .js to .ts and that was it.

Granted, it was a boilerplate project and that file was the only JavaScript file in the whole (TypeScript) project.

Solution 25:[25]

In my case due to developing a library and an app at the same time...

Moving a file, which has an import from the library, from the app to the library, resulted that the file that is now in the library would import stuff from its own dist folder..

Funny thing is.. this is actually refactoring at its best.. it kept the correct reference to the file :)

Solution 26:[26]

this config works for me

"allowJs": true