React 有望在全球范围内可用

React is expected to be globally available

我正在用 babel 和 webpack 玩 React (@13.3)。

我有一个这样定义的组件:

import BaseComponent from './BaseComponent';

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

但是我得到以下错误:

Uncaught ReferenceError: React is not defined

我理解错误:JSX 位被编译到 React.createElement(...)React 不在当前范围内,因为它没有被导入。

我的问题是: 解决此问题的干净方法是什么?我是否必须以某种方式使用 webpack 全局公开 React


使用的解决方案:

我听从了@salehen-rahman 的建议。

在我的 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'
    }]
},

我还需要修复我的测试,所以我将其添加到文件 helper.js:

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

然后使用以下命令启动我的测试:

mocha --require ./test/helper.js 'test/**/*.js'

如果您在节点模块目录中有反应,您可以在文件顶部添加 import React from 'react';

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

babel-plugin-react-require 添加到您的项目,然后修改您的 webpack 的 Babel 配置以具有类似于以下的设置:

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

现在,应用配置更新后,无需手动导入 React 即可初始化 React 组件。

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

请记住,babel-plugin-react-require 将您的代码转换为自动包含 React 导入 specific[=] 中存在 JSX 标记26=] 文件, 用于 特定文件。对于不使用 JSX 但出于某种原因需要 React 的所有其他文件,您将必须手动导入 React。

你可以使用 Webpack 的 ProvidePlugin。要使用,请更新 Webpack 配置中的插件部分以包含以下内容:

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

然而,这并不能解决测试问题..