我正在使用Webpack捆绑我的ReactJS应用程序 .
helloworld.js
import React from 'react';
export default class HelloWorld extends React.Component {
render() {
return <h2>Hello {this.props.name}!</h2>;
}
}
index.js
import ReactDOM from 'react-dom';
import HelloWorld from './helloworld';
ReactDOM.render(<HelloWorld name="World" />,
document.getElementById('container'));
webpack.config.js
module.exports = {
entry: './index.js',
output: 'bundle.js',
module: {
loaders: [
{
test: /(\.js|\.jsx)/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
}
};
当我运行 webpack-dev-server --progress --colors
时,我在浏览器 "React is not defined" 中收到错误,但如果我直接在index.js中导入React,则错误不会出现 . Why Webpack is not including React in the bundle if it is referenced in the helloworld.js file?
2 回答
webpack只是尝试通过读取其中的依赖项并将它们解析为渲染特定元素来捆绑各个模块 . 现在捆绑时
ReactDOM尝试执行
React.createElement(_Helloworld2.default, { name: 'World' }), document.getElementById('app')
函数,该函数需要React作为index.js文件中不存在的依赖项,因此它会在index.js
文件中出现错误并解决问题 . 我希望我能够解释,我的回答可以帮到你 .你缺少
import React from 'react';
陈述 . 每次在文件中编写一些JSX时都需要它,因为它被转换为React.createElement(..)
函数调用 .