Last updated: Feb 28, 2024
Reading time·2 min
The error "Cannot write file because it would overwrite input file" occurs
when we haven't specified the outDir
directory in the exclude
array in the
tsconfig.json
file.
To solve the error, make sure to exclude your build directory from being type checked and compiled.
Other common reasons the error occurs:
The first thing you should do is make sure the build directory of your project
is excluded. Open our tsconfig.json
file and look at your outDir
setting.
{ "compilerOptions": { "outDir": "build", }, "include": ["src/**/*"], "exclude": ["node_modules", "build/**/*"] }
The build
directory is where TypeScript will output the emitted files.
Make sure you have added the specified
outDir to the exclude
array
like in the example.
You might want to restart your IDE as you troubleshoot because VSCode often glitches.
Once you have excluded your build directory, try deleting it and then rerunning your build step.
The next thing you should make sure of is that you aren't importing anything from your build directory.
When using auto-imports, your IDE might have glitched and imported something
from your dist
or build
directory.
You can use the search functionality in your IDE, e.g. ctrl + shift + f
to
look for imports that look like the following (depending on how your outDir
is
named):
import {myFunction} from '../../../dist/my-folder/my-function' import {myFunction} from '../../../build/my-folder/my-function'
If you spot any imports from your build directory, update them and restart your IDE.
A circular dependency is when 2 files depend on one another. For example file
A
imports from file B
and file B
imports from file A
.
This is very problematic, especially when using monorepos. You might have 2 packages that depend on one another with mixed-up imports.
For example, make sure you don't have imports like -
import {myFunction} from '@same-package/my-function'
.
Instead, you should use a relative import in the same package, e.g.
import {myFunction} from './my-function'
.
allowJs
to false
in your tsconfig.json
fileIf the error persists, try setting the allowJs
option to false
in your
tsconfig.json
file.
{ "compilerOptions": { "allowJs": false, // ... other options }, }
The allowJs option allows
files with .js
and .jsx
extensions to be imported into your project.
This is often an issue when importing files from a build directory by mistake.
If the error persists, make sure you haven't imported your root index.ts
file
by using a relative import like import {myFunction} from '../../../'
.
Try changing the import to import {myFunction} from '../../../index'
.
I've also written a detailed guide on how to import values from another file in TS.