Skip to content

Commit

Permalink
Improve performance on plugin transform
Browse files Browse the repository at this point in the history
  • Loading branch information
wille committed Aug 21, 2024
1 parent 95e02c8 commit c440ee1
Showing 1 changed file with 30 additions and 21 deletions.
51 changes: 30 additions & 21 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,28 +48,32 @@ export default function preloadPlugin({

const foundLazyImports = new Set<string>();

const ast = parse(code, {
sourceType: 'module',
plugins: ['jsx', 'typescript'],
});

// Find React.lazy imported modules
traverse(ast, {
Import(path) {
if (!path.parent['arguments']) {
return;
}

const importArgument = path.parent['arguments'][0];

if (importArgument) {
// Dynamic import of a dynamic module is not supported
if (importArgument.type === 'StringLiteral') {
foundLazyImports.add(importArgument.value);
let ast;

// Find dynamic imports
if (code.includes(' import(')) {
ast = parse(code, {
sourceType: 'module',
plugins: ['jsx', 'typescript'],
});

traverse(ast, {
Import(path) {
if (!path.parent['arguments']) {
return;
}
}
},
});

const importArgument = path.parent['arguments'][0];

if (importArgument) {
// Dynamic import of a dynamic module is not supported
if (importArgument.type === 'StringLiteral') {
foundLazyImports.add(importArgument.value);
}
}
},
});
}

for (const importString of foundLazyImports) {
const relative = path.resolve(path.dirname(id), importString);
Expand All @@ -89,6 +93,11 @@ export default function preloadPlugin({
if (lazyImportedModules.has(id)) {
let injected = false;

ast ||= parse(code, {
sourceType: 'module',
plugins: ['jsx', 'typescript'],
});

traverse(ast, {
ExportDefaultDeclaration(path) {
const declaration = path.node.declaration;
Expand Down

0 comments on commit c440ee1

Please sign in to comment.