Automatically require React (or other implementations) when using JSX. This babel plugin inserts CommonJS style require where it detects JSX and React isn't already required (or imported using ES2015 syntax).
If you're using JSX in your React (or similar) components, you often
don't need the React
module to anything else, and it will seem as
if you have an unused require-statement. When using something like
eslint
you'd have to add a rule saying
unused React
should be ignored, but that's not always true.
With this module you'll no longer need to use this anti-pattern:
let React = require('react'); // free, seemingly unused
module.exports = function MyComponent () {
return (
<h1>Hello World!</h1>
);
};
You can instead let it be an implementation detail and write:
module.exports = function MyComponent () {
return (
<h1>Hello World!</h1>
);
};
$ npm install --save babel-plugin-transform-react-require
.babelrc
{
"plugins": ["transform-react-require"]
}
Not using React with JSX? You can define module name and module identifier
as options. For instance, if you are using dom('div', {})
instead of
React.createElement('div', {})
, you might want to require dom
, instead
of React
. In that case, you can override defaults by doing:
{
"plugins": [
["transform-react-require", {
"identifier": "dom",
"moduleName": "my-dom-library"
}]
]
}
This would cause the plugin to automatically require my-dom-library
,
when JSX syntax is detected, and store it in the identifier dom
.
$ babel --plugins transform-react-require script.js
require('babel-core').transform('code', {
plugins: ['transform-react-require']
});
Same as through the .babelrc
, you can override defaults:
require('babel-core').transform('code', {
plugins: ['transform-react-require', {
'identifier': 'dom',
'moduleName': 'my-dom-library'
}]
});