diff --git a/src/index.ts b/src/index.ts index f0f793b..5ce9fc8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -45,10 +45,29 @@ const nodeSupportsImport = ( ) ); +const extensions = Module._extensions; +const defaultLoader = extensions['.js']; + +const transformExtensions = [ + '.js', + '.cjs', + '.cts', + '.mjs', + '.mts', + '.ts', + '.tsx', + '.jsx', +]; + function transformer( module: Module, filePath: string, ) { + const shouldTransformFile = transformExtensions.some(extension => filePath.endsWith(extension)); + if (!shouldTransformFile) { + return defaultLoader(module, filePath); + } + /** * For tracking dependencies in watch mode */ @@ -81,14 +100,19 @@ function transformer( module._compile(code, filePath); } -const extensions = Module._extensions; - -/** - * Loaders for implicitly resolvable extensions - * https://github.com/nodejs/node/blob/v12.16.0/lib/internal/modules/cjs/loader.js#L1166 - */ [ - '.js', // (Handles .cjs, .cts, .mts & any explicitly specified extension that doesn't match any loaders) + /** + * Handles .cjs, .cts, .mts & any explicitly specified extension that doesn't match any loaders + * + * Any file requested with an explicit extension will be loaded using the .js loader: + * https://github.com/nodejs/node/blob/e339e9c5d71b72fd09e6abd38b10678e0c592ae7/lib/internal/modules/cjs/loader.js#L430 + */ + '.js', + + /** + * Loaders for implicitly resolvable extensions + * https://github.com/nodejs/node/blob/v12.16.0/lib/internal/modules/cjs/loader.js#L1166 + */ '.ts', '.tsx', '.jsx', diff --git a/tests/index.ts b/tests/index.ts index dc8c921..8776334 100644 --- a/tests/index.ts +++ b/tests/index.ts @@ -30,6 +30,10 @@ const nodeVersions = [ import('./specs/typescript/index.js'), node, ); + runTestSuite( + import('./specs/negative-tests.js'), + node, + ); }); } })(); diff --git a/tests/specs/negative-tests.ts b/tests/specs/negative-tests.ts new file mode 100644 index 0000000..45a77d5 --- /dev/null +++ b/tests/specs/negative-tests.ts @@ -0,0 +1,21 @@ +import path from 'path'; +import { testSuite, expect } from 'manten'; +import { createFixture } from 'fs-fixture'; +import type { NodeApis } from '../utils/node-with-loader.js'; + +export default testSuite(async ({ describe }, node: NodeApis) => { + describe('Negative tests', ({ test }) => { + test('should not load .txt files', async ({ onTestFinish }) => { + const fixture = await createFixture({ + 'file.txt': 'Hello world', + 'index.js': 'import file from "./file.txt";console.log(file);', + }); + + onTestFinish(async () => await fixture.rm()); + + const nodeProcess = await node.load(path.join(fixture.path, 'index.js')); + expect(nodeProcess.stdout).toBe(''); + expect(nodeProcess.stderr).toMatch('SyntaxError: Unexpected identifier'); + }); + }); +});