React is expected to be globally available

蓝咒 提交于 2019-11-29 13:36:26

My questions is : What's the clean way to work around this issue ? Do I have to somehow expose React globally with webpack ?

Add babel-plugin-react-require to your project, and then amend your webpack's Babel config to have settings akin to:

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

Now, once you've applied the configuration update, you can initialize 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!
);

Bear in mind though, babel-plugin-react-require transforms your code to automatically include React imports only in the presence of JSX tag in a specific file, for a specific file. For every other file that don't use JSX, but needs React for whatever reason, you will have to manually import React.

If you have react in your node modules directory you can add import React from 'react'; at the top of your file.

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

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

This, however, doesn't solve it for the tests..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!