React预计将在全球范围内推出 [英] React is expected to be globally available
问题描述
我正在玩带有babel和webpack的React(@ 13.3)。
I'm playing with React (@13.3) with babel and webpack.
我有一个像这样定义的组件:
I have a component that's defined like this:
import BaseComponent from './BaseComponent';
export default class SomeComponent extends BaseComponent {
render() {
return (
<div>
<img src="http://placekitten.com/g/900/600"/>
</div>
);
}
}
但是我收到以下错误:
未捕获的ReferenceError:未定义React
Uncaught ReferenceError: React is not defined
我明白了错误:JSX位编译成 React.createElement(...)
但 React
不在当前范围,因为它没有导入。
I understand the error: the JSX bit is compiled into React.createElement(...)
but React
isn't in the current scope since it's not imported.
我的问题是:
解决这个问题的干净方法是什么?我是否必须以某种方式在全球范围内使用webpack公开 React
?
使用的解决方案:
我跟着@ salehen-rahman建议。
I followed @salehen-rahman suggestion.
在我的webpack.config.js中:
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'
}]
},
我还需要修复我的测试,所以我将其添加到文件helper.js中:
I also needed to fix my tests, so I added this to the file helper.js:
require('babel-core/register')({
ignore: /node_modules/,
plugins: ['react-require'],
extensions: ['.js']
});
然后使用以下命令启动我的测试:
My tests are then launched with the following command:
mocha --require ./test/helper.js 'test/**/*.js'
推荐答案
我的问题是:解决这个问题的干净方法是什么?我是否必须以某种方式在全局范围内使用webpack公开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配置,使其设置类似于:
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
]
},
}
]
现在,一旦您应用了配置更新,您就可以初始化React组件而无需手动导入React。
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!
);
请记住, babel-plugin-react-require
将代码转换为在特定文件中存在JSX标记时自动包含React导入 ,用于特定文件。对于不使用JSX的每个其他文件,但出于任何原因需要React,您必须手动导入React。
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.
这篇关于React预计将在全球范围内推出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!