Skip to content

Commit

Permalink
fix(esbuild): Exclude loaders file types from the parser
Browse files Browse the repository at this point in the history
  • Loading branch information
lgollut committed Oct 10, 2023
1 parent 5888bc8 commit fd6e080
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
32 changes: 32 additions & 0 deletions packages/esbuild-plugin-ast/src/__tests__/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ describe('astParser', () => {
format: 'esm',
minify: false,
write: false,
loader: { '.json': 'json' },
plugins: [astParser(pluginOptions)],
};

Expand Down Expand Up @@ -90,4 +91,35 @@ describe('astParser', () => {
);
});
});

describe('Other file types', () => {
beforeAll(() => {
entryPoint = join(tmpDir, `/packages/${virtualPackage}/index.js`);
testFilePath = `./packages/${virtualPackage}/test-case.json`;
testFile = join(tmpDir, testFilePath);
});

beforeEach(async () => {
await writeFile(
entryPoint,
`import testCase from './test-case.json';\ntestCase.${argument};`,
);

ctx = await context({
...esbuildConfig,
entryPoints: { index: entryPoint },
});
});

it('should not parse and transform file types explicitly handled by other loaders', async () => {
const testCase = `{ "${argument}": "value" }`;
await writeFile(testFile, testCase);

const result = await ctx.rebuild();

expect((result.outputFiles as OutputFile[])[0].text).toEqual(
expect.stringContaining('value'),
);
});
});
});
12 changes: 12 additions & 0 deletions packages/esbuild-plugin-ast/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ export function astParser({ dependencies, visitor }: AstParserOptions): Plugin {
name: 'astParser',
setup(build) {
const namespace = 'ast-parser';
const excludeFileTypes = Object.keys(
build.initialOptions.loader || {},
).map((key) => key.slice(1));

/**
* Use the entry points as starting point for the plugin
Expand All @@ -41,6 +44,15 @@ export function astParser({ dependencies, visitor }: AstParserOptions): Plugin {
resolveDir: dirname(args.importer),
});

const fileType = result.path.split('.').pop();

if (fileType && excludeFileTypes.includes(fileType)) {
return {
path: result.path,
namespace: 'file',
};
}

return {
path: result.path,
namespace,
Expand Down

0 comments on commit fd6e080

Please # to comment.