Cosmiconfig TypeScript Loader
cosmiconfig-typescript-loader provides a robust TypeScript loader for `cosmiconfig`, enabling applications to load configuration files written in TypeScript (e.g., `.ts` files). It is currently at version 6.3.0, with minor and patch releases occurring as needed for dependency updates and maintenance. This package serves as a maintained successor to the abandoned `@endemolshinegroup/cosmiconfig-typescript-loader`, addressing several critical issues found in the original, such as compatibility with `cosmiconfig`'s synchronous API and providing proper TypeScript support during compilation. It leverages `jiti` for on-the-fly TypeScript compilation, supporting both CommonJS and ESM environments, making it a flexible choice for modern Node.js applications that rely on TypeScript for configuration.
Common errors
-
Error: cosmiconfig: loader for extension ".ts" must be a function.
cause Attempting to use `TypeScriptLoader` or `TypeScriptLoaderSync` without calling it as a function.fixEnsure you call the loader, e.g., `loaders: { ".ts": TypeScriptLoader() }` instead of `loaders: { ".ts": TypeScriptLoader }`. -
TypeError: explorer.load is not a function
cause Using `cosmiconfig-typescript-loader` with an incompatible or too old version of `cosmiconfig`.fixEnsure your `cosmiconfig` dependency is `^9.0.0` or higher, as required by `cosmiconfig-typescript-loader` v6. -
ReferenceError: require is not defined in ES module scope
cause Trying to use `require()` to import `cosmiconfig-typescript-loader` in an ESM context when the package is primarily designed for ESM imports.fixUse `import { TypeScriptLoader } from 'cosmiconfig-typescript-loader';` for ESM environments. If in a CJS context, you might need to enable `jiti`'s CJS fallback or ensure your project's module resolution is correctly configured. -
Error: Cannot find module 'jiti'
cause Jiti is a peer dependency of the package and might not be explicitly installed or resolved correctly in some project setups.fixManually install `jiti` as a dependency: `npm install jiti` or `yarn add jiti`.
Warnings
- breaking The primary `TypeScriptLoader` export became asynchronous in version 6.0.0. If you were previously calling `explorer.load()` without `await`, your code will now produce a Promise that needs to be awaited.
- deprecated The `TypeScriptLoaderSync` export is deprecated since version 6.0.0. This is due to `jiti`, the underlying compilation library, deprecating its synchronous import API. While still available, its use is discouraged and it may be removed in a future major version.
- breaking Node.js 16 support was dropped in version 6.0.0. This package now requires Node.js v18 or higher.
- breaking Version 5.0.0 introduced ESM support and switched from `ts-node` to `jiti` for compilation, and requires `cosmiconfig` version 8 or higher. This might affect advanced configurations or specific `tsconfig.json` setups.
- gotcha This package is a drop-in replacement for the unmaintained `@endemolshinegroup/cosmiconfig-typescript-loader`. If you were using the older package, you should switch to this one to receive updates and bug fixes.
Install
-
npm install cosmiconfig-typescript-loader -
yarn add cosmiconfig-typescript-loader -
pnpm add cosmiconfig-typescript-loader
Imports
- TypeScriptLoader
const { TypeScriptLoader } = require('cosmiconfig-typescript-loader');import { TypeScriptLoader } from 'cosmiconfig-typescript-loader'; - TypeScriptLoaderSync
import TypeScriptLoaderSync from 'cosmiconfig-typescript-loader/sync';
import { TypeScriptLoaderSync } from 'cosmiconfig-typescript-loader'; - Custom TypeScript Loader with Options
import { TypeScriptLoader } from 'cosmiconfig-typescript-loader'; const customLoader = new TypeScriptLoader();import { TypeScriptLoader } from 'cosmiconfig-typescript-loader'; const customLoader = TypeScriptLoader({ cache: false });
Quickstart
import { cosmiconfig } from "cosmiconfig";
import { TypeScriptLoader } from "cosmiconfig-typescript-loader";
interface MyConfig {
host: string;
port: number;
enabledFeatures?: string[];
}
async function loadConfig(): Promise<MyConfig | null> {
const moduleName = "my-app";
const explorer = cosmiconfig(moduleName, {
searchPlaces: [
`${moduleName}.config.ts`,
`.${moduleName}rc.ts`
],
loaders: {
".ts": TypeScriptLoader(),
},
});
// Assume 'my-app.config.ts' exists in the current directory with content like:
// export default { host: 'localhost', port: 3000 };
try {
const result = await explorer.load(process.cwd());
if (result && result.config) {
console.log("Configuration loaded successfully:", result.config);
return result.config as MyConfig;
} else {
console.log("No configuration found.");
return null;
}
} catch (error) {
console.error("Error loading configuration:", error);
throw error;
}
}
loadConfig();