Skip to content

Commit a0fd3fb

Browse files
authored
Merge pull request #32 from ljharb/less_react
[Fix] Only ensure a React import when there’s an svg import in the file.
2 parents 69fe998 + 5f9cf6d commit a0fd3fb

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

src/index.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -24,19 +24,22 @@ let ignoreRegex;
2424
export default ({ types: t }) => ({
2525
visitor: {
2626
Program: {
27-
enter({ scope, node }) {
27+
enter({ scope, node }, { file }) {
2828
if (!scope.hasBinding('React')) {
2929
const reactImportDeclaration = t.importDeclaration([
3030
t.importDefaultSpecifier(t.identifier('React')),
3131
], t.stringLiteral('react'));
3232

33-
node.body.unshift(reactImportDeclaration);
33+
file.set('ensureReact', () => { node.body.unshift(reactImportDeclaration); });
34+
} else {
35+
file.set('ensureReact', () => {});
3436
}
3537
},
3638
},
3739
ImportDeclaration(path, state) {
3840
const importPath = path.node.source.value;
3941
const { ignorePattern, caseSensitive } = state.opts;
42+
const { file } = state;
4043
if (ignorePattern) {
4144
// Only set the ignoreRegex once:
4245
ignoreRegex = ignoreRegex || new RegExp(ignorePattern);
@@ -104,6 +107,7 @@ export default ({ types: t }) => ({
104107
const svgReplacement = buildSvg(opts);
105108
path.replaceWith(svgReplacement);
106109
}
110+
file.get('ensureReact')();
107111
}
108112
},
109113
},

test/fixtures/test-no-svg-or-react.js

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import './path/to.jpg';
2+
import './code.js';
3+
4+
export default class Foo {
5+
}

test/sanity.js

+14
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,17 @@ transformFile('test/fixtures/test-case-sensitive.jsx', {
4949
throw new Error("Test failed: Expected case sensitive error wasn't thrown");
5050
}
5151
});
52+
53+
transformFile('test/fixtures/test-no-svg-or-react.js', {
54+
babelrc: false,
55+
presets: [],
56+
plugins: [
57+
'../../src/index',
58+
],
59+
}, (err, result) => {
60+
if (err) throw err;
61+
console.log('test/fixtures/test-no-svg-or-react.js', result.code);
62+
if (/React/.test(result.code)) {
63+
throw new Error('Test failed: React import was present');
64+
}
65+
});

0 commit comments

Comments
 (0)