An unknown file extension was encountered.
Production Risk
Low. This configuration error prevents the application from starting, so it is caught during development.
This error occurs in the ES module system when you try to import a file with an extension that Node.js does not recognize by default. Node.js has built-in support for `.js`, `.mjs`, `.cjs`, and `.json`. If you use another extension, like `.ts` or `.jsx`, without a custom loader or transpiler, Node.js does not know how to handle the file.
- 1Importing a file with a non-standard extension like `.ts`, `.jsx`, or `.coffee` without a loader.
- 2A typo in a file extension (e.g., `import './file.jss'`).
- 3The file extension is missing from the import path when it is required for ES modules.
This error is thrown when the ES module loader encounters an `import` statement for a file whose extension is not registered in its internal format resolver.
// In an ES module (e.g., 'index.mjs')
// Assuming 'my-typescript-file.ts' exists but no loader is configured.
try {
await import('./my-typescript-file.ts');
} catch (err) {
console.error(err.code);
}expected output
ERR_UNKNOWN_FILE_EXTENSION
Fix 1
Use a Custom Loader
WHEN You need to import files that require transpilation (e.g., TypeScript, JSX).
node --loader ts-node/esm my-app.ts
Why this works
Use a custom loader to hook into the ES module resolution process. The loader tells Node.js how to transform the file into valid JavaScript before executing it.
Fix 2
Use a Standard Extension
WHEN The file is plain JavaScript and was simply misnamed.
// Rename the file from 'my-code.txt' to 'my-code.js' import myCode from './my-code.js';
Why this works
Ensure your JavaScript files use one of the standard extensions that Node.js recognizes automatically, such as `.js` or `.mjs`.
// In an ES module (e.g., 'index.mjs')
// Assuming 'my-typescript-file.ts' exists but no loader is configured.
try {
await import('./my-typescript-file.ts');
} catch (err) {
console.error(err.code); // this triggers ERR_UNKNOWN_FILE_EXTENSIONtry {
// operation that may throw ERR_UNKNOWN_FILE_EXTENSION
riskyOperation()
} catch (err) {
if (err.code === 'ERR_UNKNOWN_FILE_EXTENSION') {
console.error('ERR_UNKNOWN_FILE_EXTENSION:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_unknown_file_extension(...args) {
// validate args here
return performOperation(...args)
}✕
https://github.com/nodejs/node/blob/main/lib/internal/modules/esm/resolve.js
More information ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev