Skip to content

Commit da9d214

Browse files
committed
[Fix] do not crash on dynamic requires
Fixes #47.
1 parent 8e281fc commit da9d214

File tree

5 files changed

+33
-4
lines changed

5 files changed

+33
-4
lines changed

src/index.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ let ignoreRegex;
2323

2424
export default ({ types: t }) => {
2525
function applyPlugin(importIdentifier, importPath, path, state) {
26+
if (typeof importPath !== 'string') {
27+
throw new TypeError('`applyPlugin` `importPath` must be a string');
28+
}
2629
const { ignorePattern, caseSensitive } = state.opts;
2730
const { file } = state;
2831
if (ignorePattern) {
@@ -110,8 +113,9 @@ export default ({ types: t }) => {
110113
},
111114
CallExpression(path, state) {
112115
const { node } = path;
113-
const filePath = node.arguments.length > 0 && node.arguments[0].value;
114-
if (node.callee.name === 'require' && t.isVariableDeclarator(path.parent)) {
116+
const requireArg = node.arguments.length > 0 ? node.arguments[0] : null;
117+
const filePath = t.isStringLiteral(requireArg) ? requireArg.value : null;
118+
if (node.callee.name === 'require' && t.isVariableDeclarator(path.parent) && filePath) {
115119
applyPlugin(path.parent.id, filePath, path.parentPath.parentPath, state);
116120
}
117121
},
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import React from 'react';
2+
3+
const MySvg = require('./close.svg');
4+
5+
export const foo = require(path.join(pkgBase, 'package.json')); // regression test
6+
7+
export default function MyFunctionIcon() {
8+
return <MySvg />;
9+
}
10+
11+
export class MyClassIcon extends React.Component {
12+
render() {
13+
return <MySvg />;
14+
}
15+
}

test/fixtures/test-import.jsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import React from 'react';
22
import MySvg from './close.svg';
33

4-
export function MyFunctionIcon() {
4+
export default function MyFunctionIcon() {
55
return <MySvg />;
66
}
77

test/fixtures/test-require.jsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import React from 'react';
22

33
const MySvg = require('./close.svg');
44

5-
export function MyFunctionIcon() {
5+
export default function MyFunctionIcon() {
66
return <MySvg />;
77
}
88

test/sanity.js

+10
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,13 @@ transformFile('test/fixtures/test-import.jsx', {
111111
}
112112
});
113113
});
114+
115+
transformFile('test/fixtures/test-dynamic-require.jsx', {
116+
presets: ['airbnb'],
117+
plugins: [
118+
'../../src/index',
119+
],
120+
}, (err, result) => {
121+
if (err) throw err;
122+
console.log('test/fixtures/test-dynamic-require.jsx', result.code);
123+
});

0 commit comments

Comments
 (0)