Skip to content

Instantly share code, notes, and snippets.

@rifler
Last active December 16, 2020 06:03
Show Gist options
  • Save rifler/8dd9308a5adc550e26b1b850180431b7 to your computer and use it in GitHub Desktop.
Save rifler/8dd9308a5adc550e26b1b850180431b7 to your computer and use it in GitHub Desktop.
load tsconfig compilerOptions, respects "extends" field
const ts = require('typescript');
const { existsSync, readFileSync } = require('fs');
const { resolve, dirname } = require('path');
const readFile = (fname) => readFileSync(fname, 'utf8');
const normalizeSlashes = (value) => value.replace(/\\/g, '/');
module.exports = ({
cwd = process.cwd(),
project,
} = {}) => {
let config = { compilerOptions: {} };
let basePath = cwd;
const configFileName = project
? resolve(cwd, project)
: ts.findConfigFile(cwd, existsSync);
if (configFileName) {
const result = ts.readConfigFile(configFileName, readFile);
if (result.error) {
console.error('ERROR IN TYPESCRIPT while reading tsconfig');
throw new Error(result.error)
}
config = result.config;
basePath = normalizeSlashes(dirname(configFileName));
}
const result = ts.parseJsonConfigFileContent(
config,
ts.sys,
basePath,
undefined,
configFileName
);
if (result.errors.length) {
console.error('ERROR IN TYPESCRIPT while parsing tsconfig');
throw new Error(result.errors[0]);
}
return result.options;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment