Typescript rootDir and outDir not working – keep compiling in src folder
If you are facing the issue where TypeScript’s rootDir
and outDir
options are not working as expected and your files keep compiling in the src
folder instead of the specified output directory, you are not alone. This problem can be frustrating, but fortunately, there are a few solutions you can try to resolve it.
Solution 1: Check your tsconfig.json file
The first thing you should do is to double-check your tsconfig.json
file. Make sure that you have correctly set the rootDir
and outDir
options. The rootDir
option specifies the root folder where your TypeScript files are located, while the outDir
option defines the output directory for the compiled JavaScript files.
Here’s an example of a correctly configured tsconfig.json
file:
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"target": "es5",
"module": "commonjs",
"strict": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
Make sure that the paths specified for rootDir
and outDir
are correct and match your project’s folder structure.
Solution 2: Clean the output directory
In some cases, the issue might be caused by cached files in the output directory. To resolve this, you can try cleaning the output directory manually. Simply delete all the files and folders in the output directory and then recompile your TypeScript files.
If you are using a build tool like npm scripts
or webpack
, you can add a custom clean task to remove the output directory before each build. Here’s an example of how you can achieve this with npm scripts
:
"scripts": {
"clean": "rm -rf dist",
"build": "npm run clean && tsc"
}
By running npm run build
, the clean
task will remove the dist
directory before the TypeScript compilation starts.
Solution 3: Use absolute paths in your import statements
Another reason why the rootDir
and outDir
options may not work as expected is due to relative import statements in your TypeScript files. If you are using relative paths like "./someModule"
in your import statements, TypeScript may still compile the files in the src
folder instead of the specified output directory.
To fix this, you can switch to using absolute paths in your import statements. This can be achieved by configuring the baseUrl
and paths
options in your tsconfig.json
file. Here’s an example:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"*": ["*"]
}
}
}
With this configuration, you can now use absolute import paths in your TypeScript files, like "@moduleName/someModule"
. TypeScript will then correctly resolve the paths and compile the files to the specified output directory.
By trying these solutions, you should be able to resolve the issue where TypeScript’s rootDir
and outDir
options are not working as expected. Remember to double-check your configuration, clean the output directory, and consider using absolute paths in your import statements.
Happy coding!
Leave a Reply