The response is expected to be available globally.

I play with React (@ 13.3) with babel and webpack.

I have a component that is defined as follows:

import BaseComponent from './BaseComponent'; export default class SomeComponent extends BaseComponent { render() { return ( <div> <img src="http://placekitten.com/g/900/600"/> </div> ); } } 

But I get the following error:

Untrained ReferenceError: React not defined

I understand the error: the JSX bit is compiled in React.createElement(...) , but React not in the current scope, since it is not imported.

My questions: What is a clean way around this problem? Do I have to somehow expose React globally with webpack?


Solution Used:

I followed the sentence @ salehen-rahman.

In my webpack.config.js:

 module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'react-hot!babel?plugins[]=react-require' }, { test: /\.css$/, loader: 'style!css!autoprefixer?browsers=last 2 versions' }] }, 

I also needed to fix my tests, so I added this to the helper.js file:

 require('babel-core/register')({ ignore: /node_modules/, plugins: ['react-require'], extensions: ['.js'] }); 

Then my tests are run using the following command:

 mocha --require ./test/helper.js 'test/**/*.js' 
+8
javascript reactjs webpack babeljs react-jsx
source share
3 answers

My questions are: what is a clean way around this problem? Do I have to somehow expose React globally with webpack?

Add babel-plugin-react-require to your project and then change the Babel configuration in webpack to have settings similar to:

 loaders: [ { test: /.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { stage: 0, optional: ['runtime'], plugins: [ 'react-require' // <-- THIS IS YOUR AMENDMENT ] }, } ] 

Now that you have applied the configuration update, you can initialize the React components without manually importing React.

 React.render( <div>Yippee! No <code>import React</code>!</div>, document.body // <-- Only for demonstration! Do not use document.body! ); 

Keep in mind that babel-plugin-react-require converts your code to automatically enable React import only if there is a JSX tag in a specific file for a specific file. For every other file that does not use JSX but needs React for any reason, you will have to manually import React.

+6
source share

If you answered in your node modules directory, you can add import React from 'react'; to the beginning of the file.

+2
source share

You can use Webpack ProvidePlugin . To use, update the plugins section in your Webpack configuration to include the following:

 plugins: [ new webpack.ProvidePlugin({ 'React': 'react' }) ] 

This, however, does not solve it for tests.

0
source share

All Articles