我无法使ReactDOM.render(...)接受任何JSX标签,但是,如果我使用React.createElement(...),它将起作用。
这是我的 index.jsx 文件:
import React from "react";
import ReactDOM from "react-dom";
// THIS WORKS!
//var elem = React.createElement('h1',{},"Hello");
//ReactDOM.render(elem, document.getElementById("content"));
// THIS DOESN'T WORK!
ReactDOM.render(<h1>Hello World!</h1>, document.getElementById("content"));
在 index.html 文件中,某个div的位置带有id =“ content”。
这是我的 package.json 文件:
{
"name": "static",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p --progress --config webpack.config.js",
"dev-build": "webpack --progress -d --config webpack.config.js",
"watch": "webpack --progress -d --config webpack.config.js --watch"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/preset-env": "^7.4.5",
"@babel/preset-react": "^7.0.0",
"webpack": "^4.35.0",
"webpack-cli": "^3.3.5"
},
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
这是我的 webpack.config.js 文件:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
};
module.exports = config;
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
我遇到的错误是:
ERROR in ./js/index.jsx 11:16
Module parse failed: Unexpected token (11:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
|
> ReactDOM.render(<h1>Hello World!</h1>, document.getElementById("content"));
|
解决方案:
所有 webpack.config.js 中的第1个错误(请参见已接受的答案)。
之后,我必须使用npm install -D babel-loader @babel/core @babel/preset-env webpack
安装 babel-loader ,然后在其他配置的相同路径下创建 .babelrc 文件。文件,内容:
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
答案 0 :(得分:1)
您将规则放置在错误的位置。
正确的配置是:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
module.exports = config;