fix(v2): avoid duplicated imports in npm2yarn plugin (#4964)

* fix(v2): avoid duplicated imports in npm2yarn plugin

* Better testing
This commit is contained in:
Alexey Pyltsyn 2021-06-15 15:43:23 +03:00 committed by GitHub
parent c8b9061f6c
commit ace285b3b5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 91 additions and 1 deletions

View file

@ -1,5 +1,61 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`npm2yarn plugin test: already imported tabs components above are not re-imported 1`] = `
"import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
<Tabs defaultValue=\\"npm\\" values={[
{ label: 'npm', value: 'npm', },
{ label: 'Yarn', value: 'yarn', },
]}
>
<TabItem value=\\"npm\\">
\`\`\`bash
$ npm install --global docusaurus
\`\`\`
</TabItem>
<TabItem value=\\"yarn\\">
\`\`\`bash
$ yarn add --global docusaurus
\`\`\`
</TabItem>
</Tabs>
"
`;
exports[`npm2yarn plugin test: already imported tabs components below are not re-imported 1`] = `
"<Tabs defaultValue=\\"npm\\" values={[
{ label: 'npm', value: 'npm', },
{ label: 'Yarn', value: 'yarn', },
]}
>
<TabItem value=\\"npm\\">
\`\`\`bash
$ npm install --global docusaurus
\`\`\`
</TabItem>
<TabItem value=\\"yarn\\">
\`\`\`bash
$ yarn add --global docusaurus
\`\`\`
</TabItem>
</Tabs>
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
"
`;
exports[`npm2yarn plugin test: installation file 1`] = `
"import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

View file

@ -0,0 +1,7 @@
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
```bash npm2yarn
$ npm install --global docusaurus
```

View file

@ -0,0 +1,7 @@
```bash npm2yarn
$ npm install --global docusaurus
```
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

View file

@ -50,4 +50,20 @@ describe('npm2yarn plugin', () => {
expect(result).toMatchSnapshot();
});
test('test: already imported tabs components above are not re-imported', async () => {
const result = await processFixture('import-tabs-above', {
staticDir,
});
expect(result).toMatchSnapshot();
});
test('test: already imported tabs components below are not re-imported', async () => {
const result = await processFixture('import-tabs-below', {
staticDir,
});
expect(result).toMatchSnapshot();
});
});

View file

@ -57,7 +57,11 @@ const nodeForImport = {
module.exports = (options = {}) => {
const {sync = false} = options;
let transformed = false;
let alreadyImported = false;
const transformer = (node) => {
if (node.type === 'import' && node.value.includes('@theme/Tabs')) {
alreadyImported = true;
}
if (matchNode(node)) {
transformed = true;
return transformNode(node, sync);
@ -74,7 +78,7 @@ module.exports = (options = {}) => {
}
}
}
if (node.type === 'root' && transformed) {
if (node.type === 'root' && transformed && !alreadyImported) {
node.children.unshift(nodeForImport);
}
return null;