gpt4 book ai didi

javascript - ReactDOM.render 不接受 JSX

转载 作者:行者123 更新时间:2023-12-02 23:24:26 25 4
gpt4 key购买 nike

我无法让 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 文件中,某处有一个 id="content"的 div。

这是我的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中的第一个是错误的(请参阅已接受的答案)。之后,我必须使用 npm install -D babel-loader @babel/core @babel/preset-env webpack 安装 babel-loader ,然后创建 .babelrc 文件位于其他配置的同一路径中。文件,内容为:

{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

最佳答案

您将规则放在了错误的位置。

正确的配置是:

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;

关于javascript - ReactDOM.render 不接受 JSX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56809239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com