Skip to content

Commit

Permalink
fix: Fix broken imports for components with the same name imported fr…
Browse files Browse the repository at this point in the history
…om different folders (#1567)

Closes #1566
  • Loading branch information
mitsuruog committed Mar 26, 2020
1 parent 3469cbb commit b03c207
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
14 changes: 14 additions & 0 deletions src/client/utils/__tests__/transpileImports.spec.ts
Expand Up @@ -85,6 +85,20 @@ const C = cat$0.C;
`);
});

describe.each([
['./cat/capybara/hamster', '__cat_capybara_hamster'],
['../cat/capybara/hamster', '___cat_capybara_hamster'],
['cat/capybara/hamster', 'cat_capybara_hamster'],
])('transpile default imports via relative path', (modulePath, transpiled) => {
test(`${modulePath}`, () => {
const result = transpileImports(`import B from '${modulePath}'`);
expect(result).toMatchInlineSnapshot(`
"const ${transpiled}$0 = require('${modulePath}');
const B = ${transpiled}$0.default || ${transpiled}$0;"
`);
});
});

test('return code if there are no imports', () => {
const code = `<Button />`;
const result = transpileImports(code);
Expand Down
11 changes: 2 additions & 9 deletions src/client/utils/rewriteImports.ts
Expand Up @@ -4,7 +4,7 @@
const UNNAMED = /import\s*['"]([^'"]+)['"];?/gi;
const NAMED = /import\s*(\*\s*as)?\s*(\w*?)\s*,?\s*(?:\{([\s\S]*?)\})?\s*from\s*['"]([^'"]+)['"];?/gi;

function alias(key: string): {key: string; name: string} {
function alias(key: string): { key: string; name: string } {
key = key.trim();
const name = key.split(' as ');
if (name.length > 1) {
Expand All @@ -15,13 +15,7 @@ function alias(key: string): {key: string; name: string} {

let num: number;
function generate(keys: string[], dep: string, base: string, fn: string): string {
const tmp =
(dep
.split('/')
.pop() as string)
.replace(/\W/g, '_') +
'$' +
num++; // uniqueness
const tmp = dep.replace(/\W/g, '_') + '$' + num++; // uniqueness
const name = alias(tmp).name;

dep = `${fn}('${dep}')`;
Expand All @@ -41,7 +35,6 @@ function generate(keys: string[], dep: string, base: string, fn: string): string
return out;
}


export default function(str: string, fn = 'require'): string {
num = 0;
return str
Expand Down

0 comments on commit b03c207

Please sign in to comment.