The "output directory" in tsconfig.json is primarily controlled by the compilerOptions.outDir property. There's also compilerOptions.outFile for single-file output, and compilerOptions.declarationDir for declaration files.
Here's how you can get this information:
1. Programmatically (Recommended for Tooling)
The most robust and accurate way is to use the TypeScript compiler API itself, as it handles extends, default values, and path resolution correctly.
import * as ts from 'typescript';
import * as path from 'path';
import * as fs from 'fs';
/**
* Reads a tsconfig.json file and extracts the resolved output directory.
* @param tsconfigPath The absolute or relative path to the tsconfig.json file.
* @returns The absolute path to the output directory, or null if not found/resolved.
*/
function getTsOutputDirectory(tsconfigPath: string): string | null {
const configPath = path.resolve(tsconfigPath); // Ensure absolute path
const configDir = path.dirname(configPath);
// 1. Read the tsconfig.json file
const configFileText = ts.sys.readFile(configPath);
if (!configFileText) {
console.error(`Error: Could not read tsconfig.json at ${configPath}`);
return null;
}
// 2. Parse the JSON content
const result = ts.parseConfigFileTextToJson(configPath, configFileText);
if (result.error) {
console.error(`Error parsing tsconfig.json: ${result.error.messageText}`);
return null;
}
const configObject = result.config;
// 3. Parse the configuration, resolving extends, includes, excludes, and options
// This is crucial for getting the final, resolved compiler options.
const parsedCommandLine = ts.parseJsonConfigFileContent(
configObject,
ts.sys,
configDir, // Base directory for resolving paths
undefined, // Existing options to merge (none initially)
configPath // Path of the tsconfig file
);
if (parsedCommandLine.errors.length > 0) {
// You might want to log these errors, but they don't necessarily prevent getting outDir
// ts.parseJsonConfigFileContent will still return an object even with some errors.
parsedCommandLine.errors.forEach(error => {
console.warn(`TsConfig parsing warning/error: ${error.messageText}`);
});
}
const compilerOptions = parsedCommandLine.options;
let outputDir: string | undefined;
if (compilerOptions.outFile) {
// If outFile is specified, the output is a single file. The directory is its parent.
outputDir = path.dirname(compilerOptions.outFile);
} else if (compilerOptions.outDir) {
// If outDir is specified, that's the primary output directory.
outputDir = compilerOptions.outDir;
} else if (compilerOptions.declarationDir) {
// If only declarationDir is specified, it might imply the output location for JS as well,
// or it's a separate output. We prioritize outDir/outFile.
// If outDir is NOT specified but declarationDir IS, the JS output usually goes alongside the TS files
// or into the rootDir if that's specified.
// For simplicity, we prioritize outDir/outFile first, then consider declarationDir.
// If neither outDir nor outFile is present, and declarationDir is,
// the *main* JS output often defaults to the `rootDir` or the `tsconfig.json` directory.
// The `declarationDir` is specifically for `.d.ts` files.
// For this function, we're trying to find the JS output directory.
// We'll return null or a default if no explicit outDir/outFile is found.
}
if (outputDir) {
// The paths returned by parseJsonConfigFileContent are already absolute if they resolve.
// If they are explicitly relative in tsconfig.json, they are resolved against configDir.
return path.resolve(outputDir);
}
// Fallback: If no outDir/outFile is specified, TypeScript often outputs
// to the `rootDir` or the directory containing the `tsconfig.json` file.
// parseJsonConfigFileContent won't set outDir if it's not explicitly present.
// So, we need to handle the default behavior if outDir is missing.
// This is typically where the source files are, or where `rootDir` points to.
if (compilerOptions.rootDir) {
return path.resolve(compilerOptions.rootDir);
} else {
// Default behavior: output to the directory where tsconfig.json resides
return configDir;
}
}
// --- Example Usage ---
// Create a dummy tsconfig.json for testing
const testTsConfigPath = path.join(__dirname, 'test-tsconfig.json');
fs.writeFileSync(testTsConfigPath, JSON.stringify({
compilerOptions: {
target: "es5",
module: "commonjs",
outDir: "./dist", // Example outDir
declaration: true,
declarationDir: "./types"
},
include: ["src/**/*"]
}, null, 2));
const testTsConfigOutFile = path.join(__dirname, 'test-tsconfig-outfile.json');
fs.writeFileSync(testTsConfigOutFile, JSON.stringify({
compilerOptions: {
target: "es5",
outFile: "./bundle.js", // Example outFile
},
include: ["src/**/*"]
}, null, 2));
const testTsConfigNoOut = path.join(__dirname, 'test-tsconfig-no-out.json');
fs.writeFileSync(testTsConfigNoOut, JSON.stringify({
compilerOptions: {
target: "es2016",
module: "esnext",
rootDir: "./src"
},
include: ["src/**/*"]
}, null, 2));
const testTsConfigBare = path.join(__dirname, 'test-tsconfig-bare.json');
fs.writeFileSync(testTsConfigBare, JSON.stringify({
compilerOptions: {
target: "esnext"
}
}, null, 2));
console.log(`\n--- Test Cases ---`);
// Test 1: With outDir
const outDir1 = getTsOutputDirectory(testTsConfigPath);
console.log(`TsConfig with outDir: ${testTsConfigPath}`);
console.log(`Resolved output directory: ${outDir1}`);
console.log(`Expected: ${path.resolve(__dirname, 'dist')}\n`);
// Test 2: With outFile
const outDir2 = getTsOutputDirectory(testTsConfigOutFile);
console.log(`TsConfig with outFile: ${testTsConfigOutFile}`);
console.log(`Resolved output directory: ${outDir2}`);
console.log(`Expected: ${path.resolve(__dirname)}\n`);
// Test 3: With no explicit outDir/outFile, but with rootDir
const outDir3 = getTsOutputDirectory(testTsConfigNoOut);
console.log(`TsConfig with no explicit outDir/outFile, but with rootDir: ${testTsConfigNoOut}`);
console.log(`Resolved output directory: ${outDir3}`);
console.log(`Expected: ${path.resolve(__dirname, 'src')}\n`);
// Test 4: Barebones tsconfig (output to tsconfig dir)
const outDir4 = getTsOutputDirectory(testTsConfigBare);
console.log(`TsConfig barebones (no outDir, outFile, rootDir): ${testTsConfigBare}`);
console.log(`Resolved output directory: ${outDir4}`);
console.log(`Expected: ${path.resolve(__dirname)}\n`);
// Clean up dummy files
fs.unlinkSync(testTsConfigPath);
fs.unlinkSync(testTsConfigOutFile);
fs.unlinkSync(testTsConfigNoOut);
fs.unlinkSync(testTsConfigBare);
Key Points for Programmatic Access:
ts.parseConfigFileTextToJson: Parses the raw JSON file content.
ts.parseJsonConfigFileContent: This is the most important step. It takes the parsed JSON and fully resolves all configuration options, including:
- Applying default values.
- Resolving
extends properties.
- Normalizing and resolving paths (so
parsedCommandLine.options.outDir will often be an absolute path if successfully resolved).
- Handling
include/exclude patterns.
parsedCommandLine.options.outDir: This is the property you're looking for.
parsedCommandLine.options.outFile: If this is present, the output is a single file, and its directory is the output directory.
- Defaults: If neither
outDir nor outFile is specified, the TypeScript compiler defaults to placing output files relative to the rootDir (if specified) or the directory containing the tsconfig.json file. The code above reflects this fallback.
declarationDir: Remember this is for .d.ts files. If you only care about where the compiled JavaScript goes, focus on outDir and outFile. If declarationDir is the only output-related option, it usually means the JS output goes elsewhere (e.g., alongside sources).
2. Manually Inspecting tsconfig.json
Open your tsconfig.json file in a text editor and look for the compilerOptions section:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "./dist", // <--- This is your output directory
"rootDir": "./src", // <--- Source root (if outDir not set, output might be relative to this)
"declaration": true,
"declarationDir": "./types", // <--- Output directory for declaration files (.d.ts)
"outFile": "./bundle.js" // <--- If this is present, output is a single file, directory is its parent
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}
outDir: If present, this specifies the output directory for all compiled JavaScript files. It's usually relative to the tsconfig.json file.
outFile: If present, all TypeScript files are concatenated into a single JavaScript file. The output directory would then be the directory containing this outFile.
declarationDir: This is specifically for TypeScript declaration files (.d.ts). Your JavaScript output might go elsewhere.
- No
outDir or outFile: If neither is specified, TypeScript will typically emit JavaScript files alongside their corresponding TypeScript source files, or relative to the rootDir if it's set. The most common default output location for the JavaScript files will be the tsconfig.json file's directory, or the rootDir if specified.
3. Using tsc --showConfig (Less Direct)
You can run the TypeScript compiler with the --showConfig flag to see the resolved configuration:
tsc --showConfig
This will print the fully resolved tsconfig.json (after applying extends, defaults, etc.) to your console. You can then manually look for outDir or outFile in the output.
Example output:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "/Users/youruser/yourproject/dist", // <--- Absolute path shown here
"rootDir": "/Users/youruser/yourproject/src",
// ... other options
},
// ...
}
Caveat: Parsing the output of tsc --showConfig programmatically can be brittle as it's meant for human readability, not machine parsing. The programmatic method using the TypeScript API is far superior for this purpose.