Skip to content

Commit

Permalink
fix: use a better exp to replace modules
Browse files Browse the repository at this point in the history
  • Loading branch information
homer0 committed May 17, 2022
1 parent 0069848 commit 5902cee
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 7 deletions.
11 changes: 9 additions & 2 deletions src/transformer.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,15 @@ const transform = (file, api, options) => {
.replaceWith((item) => {
const importPath = item.value.source.value;
const info = cjs2esm.modules.find((mod) => importPath.startsWith(mod.name));
const find = info.find ? new RegExp(info.find) : new RegExp(`^${info.name}`);
const replacement = importPath.replace(find, info.path);
let replacement;
if (info.find) {
replacement = importPath.replace(new RegExp(info.find), info.path);
} else {
replacement = importPath.replace(
new RegExp(`^${info.name}($|\\/)`),
(match, endChar) => (endChar.endsWith('/') ? `${info.path}/` : info.path),
);
}

return j.importDeclaration(item.value.specifiers, j.literal(replacement));
});
Expand Down
30 changes: 25 additions & 5 deletions tests/transformer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,22 @@ describe('transformer', () => {
},
},
},
{
value: {
specifiers: 'specifier',
source: {
value: 'lodash',
},
},
},
{
value: {
specifiers: 'specifier',
source: {
value: 'lodash-es',
},
},
},
];
let currentNodes = nodes.slice();
const message = 'done';
Expand All @@ -430,10 +446,6 @@ describe('transformer', () => {
currentNodes = currentNodes.filter(fn);
return ast;
});
ast.filter.mockImplementationOnce((fn) => {
currentNodes = currentNodes.filter(fn);
return ast;
});
ast.replaceWith.mockImplementationOnce((fn) => {
currentNodes = currentNodes.map((item) => ({
value: {
Expand Down Expand Up @@ -469,6 +481,7 @@ describe('transformer', () => {
find: 'par\\w+or',
path: 'parserror/esm',
},
{ name: 'lodash', path: 'lodash-es' },
],
};
const options = { cjs2esm };
Expand All @@ -479,11 +492,18 @@ describe('transformer', () => {
path: deepAssignPath,
}));
utils.getAbsPathInfoSync.mockImplementationOnce(() => null);
utils.getAbsPathInfoSync.mockImplementationOnce(() => null);
utils.getAbsPathInfoSync.mockImplementationOnce(() => null);
let result = null;
// When
result = transformer(file, api, options);
// Then
expect(result).toBe(message);
expect(currentNodes).toEqual(['wootils/esm/shared/deepAssign.js', 'parserror/esm']);
expect(currentNodes).toEqual([
'wootils/esm/shared/deepAssign.js',
'parserror/esm',
'lodash-es',
'lodash-es',
]);
});
});

0 comments on commit 5902cee

Please sign in to comment.