Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions packages/cli-config/src/__tests__/loadTypeScriptConfig-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {defaultLoaders, defaultLoadersSync} from 'cosmiconfig';
import {
loadTypeScriptConfig,
loadTypeScriptConfigSync,
} from '../loadTypeScriptConfig';

jest.mock('cosmiconfig', () => ({
defaultLoaders: {'.ts': jest.fn(), '.js': jest.fn()},
defaultLoadersSync: {'.ts': jest.fn(), '.js': jest.fn()},
}));

const tsLoader = defaultLoaders['.ts'] as jest.Mock;
const jsLoader = defaultLoaders['.js'] as jest.Mock;
const tsLoaderSync = defaultLoadersSync['.ts'] as jest.Mock;
const jsLoaderSync = defaultLoadersSync['.js'] as jest.Mock;

const FILE = '/project/react-native.config.ts';
const config = {assets: ['./fonts']};
const typescript7Error = new TypeError(
`TypeScript Error in ${FILE}:\ntypescript.findConfigFile is not a function`,
);

function setNativeTypeScript(value: unknown) {
Object.defineProperty(process.features, 'typescript', {
value,
configurable: true,
});
}

beforeEach(() => {
jest.resetAllMocks();
setNativeTypeScript('strip');
});

describe('loadTypeScriptConfig', () => {
it('uses the typescript loader when it works', async () => {
tsLoader.mockResolvedValue(config);

await expect(loadTypeScriptConfig(FILE, '')).resolves.toBe(config);
expect(jsLoader).not.toHaveBeenCalled();
});

it('loads the file natively when typescript has no compiler API', async () => {
tsLoader.mockRejectedValue(typescript7Error);
jsLoader.mockResolvedValue(config);

await expect(loadTypeScriptConfig(FILE, '')).resolves.toBe(config);
expect(jsLoader).toHaveBeenCalledWith(FILE, '');
});

it('does not hide other typescript errors', async () => {
const syntaxError = new SyntaxError("TypeScript Error: ';' expected");
tsLoader.mockRejectedValue(syntaxError);

await expect(loadTypeScriptConfig(FILE, '')).rejects.toBe(syntaxError);
expect(jsLoader).not.toHaveBeenCalled();
});

it('explains what to do when Node cannot load TypeScript', async () => {
setNativeTypeScript(undefined);
tsLoader.mockRejectedValue(typescript7Error);
jsLoader.mockRejectedValue(new SyntaxError('Unexpected token'));

await expect(loadTypeScriptConfig(FILE, '')).rejects.toThrow(
/cannot load TypeScript files natively/,
);
});

it('explains that Node does not load TypeScript from node_modules', async () => {
const nodeModulesError = Object.assign(new Error('unsupported'), {
code: 'ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING',
});
tsLoader.mockRejectedValue(typescript7Error);
jsLoader.mockRejectedValue(nodeModulesError);

await expect(loadTypeScriptConfig(FILE, '')).rejects.toThrow(
/does not load TypeScript files from node_modules/,
);
});
});

describe('loadTypeScriptConfigSync', () => {
it('uses the typescript loader when it works', () => {
tsLoaderSync.mockReturnValue(config);

expect(loadTypeScriptConfigSync(FILE, '')).toBe(config);
expect(jsLoaderSync).not.toHaveBeenCalled();
});

it('loads the file natively and unwraps the default export', () => {
tsLoaderSync.mockImplementation(() => {
throw typescript7Error;
});
jsLoaderSync.mockReturnValue({__esModule: true, default: config});

expect(loadTypeScriptConfigSync(FILE, '')).toBe(config);
});
});
71 changes: 71 additions & 0 deletions packages/cli-config/src/loadTypeScriptConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import {defaultLoaders, defaultLoadersSync} from 'cosmiconfig';
import type {Loader, LoaderSync} from 'cosmiconfig';

/**
* cosmiconfig 9 compiles `.ts` files with the `typescript` package of the
* project. TypeScript 7 no longer ships that compiler API, so the default
* loader throws `typescript.findConfigFile is not a function`. In that case we
* let Node load the file with its own TypeScript support instead.
*/
const MISSING_COMPILER_API =
/typescript\.(findConfigFile|readConfigFile|transpileModule)|ts\.(findConfigFile|readConfigFile|transpileModule)/;

function isMissingCompilerApi(error: unknown): boolean {
const message = (error as Error | undefined)?.message ?? '';
return (
/is not a function/.test(message) && MISSING_COMPILER_API.test(message)
);
}

function explainNativeLoadError(filepath: string, error: unknown): unknown {
// `process.features.typescript` is only set on Node.js versions that can
// strip types, so on older ones the file just fails to parse.
if (!(process.features as {typescript?: unknown}).typescript) {
return new Error(
`Failed to load ${filepath}: the installed "typescript" package cannot compile it and this version of Node.js (${process.version}) cannot load TypeScript files natively. Use Node.js 22.18 or newer, or write the configuration as react-native.config.js.`,
);
}
if (
(error as NodeJS.ErrnoException)?.code ===
'ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING'
) {
return new Error(
`Failed to load ${filepath}: Node.js does not load TypeScript files from node_modules and the installed "typescript" package cannot compile it. Ask the package author to ship react-native.config.js, or use a version of "typescript" that provides the compiler API.`,
);
}
return error;
}

function unwrapDefaultExport(mod: any) {
return mod && mod.__esModule ? mod.default : mod;
}

export const loadTypeScriptConfig: Loader = async (filepath, content) => {
try {
return await defaultLoaders['.ts'](filepath, content);
} catch (error) {
if (!isMissingCompilerApi(error)) {
throw error;
}
try {
return await defaultLoaders['.js'](filepath, content);
} catch (nativeError) {
throw explainNativeLoadError(filepath, nativeError);
}
}
};

export const loadTypeScriptConfigSync: LoaderSync = (filepath, content) => {
try {
return defaultLoadersSync['.ts'](filepath, content);
} catch (error) {
if (!isMissingCompilerApi(error)) {
throw error;
}
try {
return unwrapDefaultExport(defaultLoadersSync['.js'](filepath, content));
} catch (nativeError) {
throw explainNativeLoadError(filepath, nativeError);
}
}
};
8 changes: 8 additions & 0 deletions packages/cli-config/src/readConfigFromDisk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import type {
} from '@react-native-community/cli-types';
import {logger, inlineString} from '@react-native-community/cli-tools';
import pico from 'picocolors';
import {
loadTypeScriptConfig,
loadTypeScriptConfigSync,
} from './loadTypeScriptConfig';

/**
* Places to look for the configuration file.
Expand Down Expand Up @@ -43,6 +47,7 @@ export async function readConfigFromDiskAsync(
const explorer = cosmiconfig('react-native', {
stopDir: rootFolder,
searchPlaces,
loaders: {'.ts': loadTypeScriptConfig},
});

const searchResult = await explorer.search(rootFolder);
Expand All @@ -58,6 +63,7 @@ export function readConfigFromDisk(rootFolder: string): UserConfig {
const explorer = cosmiconfigSync('react-native', {
stopDir: rootFolder,
searchPlaces: searchPlacesForCJS,
loaders: {'.ts': loadTypeScriptConfigSync},
});

const searchResult = explorer.search(rootFolder);
Expand Down Expand Up @@ -100,6 +106,7 @@ export async function readDependencyConfigFromDiskAsync(
const explorer = cosmiconfig('react-native', {
stopDir: rootFolder,
searchPlaces,
loaders: {'.ts': loadTypeScriptConfig},
});

const searchResult = await explorer.search(rootFolder);
Expand All @@ -118,6 +125,7 @@ export function readDependencyConfigFromDisk(
const explorer = cosmiconfigSync('react-native', {
stopDir: rootFolder,
searchPlaces: searchPlacesForCJS,
loaders: {'.ts': loadTypeScriptConfigSync},
});

const searchResult = explorer.search(rootFolder);
Expand Down
Loading