我正试图通过运行一个基本程序来学习ReactJS。
webpack.config.js
var config = {
entry: './main.js',
output: {
path: './',
filename: 'index.js'
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.experts = config;
软件包.json
{
"name": "reactapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.11.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"webpack": "^1.13.1",
"webpack-dev-server": "^1.14.1"
}
}
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
"Hello, world."
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script type="text/javascript" src = "index.js"></script>
</body>
</html>
在启动服务器时,我看到一个没有内容的空页面。HTML页面在那里,但看不到React要添加到DOM中的部分。
index.js被设置为将包含我们捆绑的应用程序的文件,但浏览器控制台显示"加载资源index.js(404)失败"错误。如果我将HTML中script标记的src属性更改为main.js,那么导入语句会得到一个SyntaxError。
我怀疑问题是没有正确地将Babel或其他依赖项与我的包链接起来。
在webpack.config.js
内部有打字错误,必须是exports
而不是experts
module.exports = config;
^
在这种情况下,您不会从webpack.config.js
导出配置,而webpack
不知道您的自定义配置,而是使用默认配置。
我认为webpack.config.js
会像一样
devtool: 'eval',
entry: './src/index',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
module: {
loaders: [{
test: /.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname,
}],
}
和<script>
<script type="text/javascript" src = "/static/bundle.js"></script>