Skip to content

Commit

Permalink
feat: run plugin also on Program exit to handle dynamically added imp…
Browse files Browse the repository at this point in the history
…orts from other transforms (#269)
  • Loading branch information
danez authored and tleunen committed Feb 8, 2018
1 parent 3a0e1dd commit 12a2d07
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/index.js
Expand Up @@ -18,6 +18,9 @@ const visitor = {
enter(programPath, state) {
programPath.traverse(importVisitors, state);
},
exit(programPath, state) {
programPath.traverse(importVisitors, state);
},
},
};

Expand All @@ -29,7 +32,14 @@ export default ({ types }) => ({

const currentFile = file.opts.filename;
this.normalizedOpts = normalizeOptions(currentFile, this.opts);
// We need to keep track of all handled nodes so we do not try to transform them twice,
// because we run before (enter) and after (exit) all nodes are handled
this.moduleResolverVisited = new Set();
},

visitor,

post() {
this.moduleResolverVisited.clear();
},
});
5 changes: 5 additions & 0 deletions src/transformers/call.js
Expand Up @@ -6,12 +6,17 @@ import {


export default function transformCall(nodePath, state) {
if (state.moduleResolverVisited.has(nodePath)) {
return;
}

const calleePath = nodePath.get('callee');
const isNormalCall = state.normalizedOpts.transformFunctions.some(
pattern => matchesPattern(state.types, calleePath, pattern),
);

if (isNormalCall || isImportCall(state.types, nodePath)) {
state.moduleResolverVisited.add(nodePath);
mapPathString(nodePath.get('arguments.0'), state);
}
}
5 changes: 5 additions & 0 deletions src/transformers/import.js
Expand Up @@ -2,5 +2,10 @@ import { mapPathString } from '../utils';


export default function transformImport(nodePath, state) {
if (state.moduleResolverVisited.has(nodePath)) {
return;
}
state.moduleResolverVisited.add(nodePath);

mapPathString(nodePath.get('source'), state);
}
22 changes: 22 additions & 0 deletions test/dynamicImport.test.js
Expand Up @@ -56,4 +56,26 @@ describe('import()', () => {

expect(result.code).toBe('import("").then(() => {}).catch(() => {});');
});

it('should handle imports added by other transforms', () => {
const options = {
...transformerOpts,
plugins: [
function fakePlugin({ types }) {
return {
visitor: {
Identifier(path) {
path.replaceWith(types.Import());
},
},
};
},
...transformerOpts.plugins,
],
};
const code = 'boo("components/Header/SubHeader");';
const result = transform(code, options);

expect(result.code).toBe('import("./test/testproject/src/components/Header/SubHeader");');
});
});

0 comments on commit 12a2d07

Please sign in to comment.