Skip to content

Commit

Permalink
Skip processing if di already processed (#95)
Browse files Browse the repository at this point in the history
  • Loading branch information
albertogasparin authored Oct 23, 2024
1 parent 24d8867 commit cecd164
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
22 changes: 22 additions & 0 deletions src/babel/__tests__/unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,28 @@ describe('babel plugin', () => {
);
});

it('should skip processing the file if di() already processed', () => {
const input = `
import { di as _di } from "react-magnetic-di";
import React from 'react';
import Modal from 'modal';
function MyComponent() {
const [_Modal] = _di([Modal], MyComponent);
return <_Modal />;
}
`;
expect(babel(input)).toMatchInlineSnapshot(`
"import { di as _di } from "react-magnetic-di";
import React from 'react';
import Modal from 'modal';
function MyComponent() {
const [_Modal] = _di([Modal], MyComponent);
return __jsx(_Modal, null);
}"
`);
});

it('should add di to all top level functions', () => {
const input = `
import React, { memo, forwardRef } from 'react';
Expand Down
24 changes: 15 additions & 9 deletions src/babel/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,16 +129,22 @@ module.exports = function (babel) {

state.findDiIndentifier(t, path.node.body, path.scope);

collectDiReferencePaths(t, state.diIdentifier, path.scope).forEach(
(p, i, arr) => {
const hasMulti =
p.getFunctionParent() === arr[i + 1]?.getFunctionParent();
if (isEnabled && !hasMulti) state.addDi(p);
else p.parentPath.remove();
}
const diRefPaths = collectDiReferencePaths(
t,
state.diIdentifier,
path.scope
);

if (!isEnabled) return;
diRefPaths.forEach((p, i, arr) => {
const hasMulti =
p.getFunctionParent() === arr[i + 1]?.getFunctionParent();
if (isEnabled && !hasMulti) state.addDi(p);
else p.parentPath.remove();
});

const alreadyProcessed = diRefPaths.some((p) =>
p.parentPath?.parentPath?.isVariableDeclarator()
);
if (!isEnabled || alreadyProcessed) return;

collectDepsReferencePaths(t, path.get('body')).forEach((p) =>
state.addDependency(p)
Expand Down

0 comments on commit cecd164

Please sign in to comment.