所以上周我得知我需要学习react.js。我的javascript是有限的但是到底是什么。
我正在尝试通常的“Hello World”项目来感受。
当我使用以下index.js文件运行webpack -p时,它可以正常工作:
index.js
var app = document.getElementById('app');
app.innerHTML = 'Hello World!'
但是当我将index.js更改为以下内容时:
index.js
var React = require('react');
var ReactDOM = require('react-dom');
var HelloWorld = react.createClass({
render: function() {
return (
<div>Hello World</div>
)
}
});
ReactDOM.render(
<HelloWorld/>,
document.getElementById('app')
)
我收到以下错误:
C:\Programming\reactFiles>npm run production
> reactfiles@1.0.0 production C:\Programming\reactFiles
> webpack -p
Hash: 21e367e251c35209471c
Version: webpack 1.12.14
Time: 692ms
Asset Size Chunks Chunk Names
index_bundle.js 289 bytes 0 [emitted] main
index.html 315 bytes [emitted]
[0] multi main 28 bytes {0} [built] [1 error]
+ 1 hidden modules
ERROR in ./app/index.js
Module build failed: SyntaxError: C:/Programming/reactFiles/app/index.js: Unexpected token (7:12)
5 | render: function() {
6 | return (
> 7 | <div>Hello World</div>
| ^
8 | )
9 | }
10 | });
at parser.pp //.......for about 30 lines. I can add them if it helps
@ multi main
Child html-webpack-plugin for "index.html":
+ 3 hidden modules
我的package.json:
{
"name": "reactfiles",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"production": "webpack -p",
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^0.14.7",
"react-dom": "^0.14.7"
},
"devDependencies": {
"babel-core": "^6.6.5",
"babel-loader": "^6.2.4",
"babel-preset-react": "^6.5.0",
"html-webpack-plugin": "^2.9.0",
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
}
}
webpack.config.js:
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
})
module.exports = {
entry: [
'./app/index.js'
],
output: {
path: __dirname + '/dist',
filename: "index_bundle.js"
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}
]
},
plugins: [HtmlWebpackPluginConfig]
}
我看到其他问题类似,但没有找到有效的答案。
有什么想法吗?
答案 0 :(得分:1)
你的babel-loader缺少配置。
{
test: /\.js$/,
loader: "babel",
exclude: /node_modules/,
query: {
presets: ["react"]
}
}
瞧,它有效。 :)
参考:https://github.com/babel/babel-loader#usage
我刚刚意识到,我有点把它扔进去而没有解释:当指定一个加载器时,不需要来编写完整的加载器名称。您可以从名称中省略-loader
,Webpack也会找到它!