gpt4 book ai didi

javascript - ReactJS代码编译成功,但未在浏览器上打印

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

经过大量努力,我能够安装和配置 ReactJS。执行“npm start”命令后,代码“已成功编译”并将我重定向到网络浏览器。但是没有任何输出,即浏览器是“空白”。有人能解决这个问题吗? (我的第一篇文章在这里)

另请检查我使用过的代码..

index.html文件

<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = 'index_bundle.js'></script>
</body>
</html>

App.js

import React, { component } from 'react';
class App extends Component {
render(){
return(
<div>
<h1> Hello World</h1>
<p>Hello </p>
</div>
);
}
}
export default App;

ma​​in.js

import React from 'react';
import { render } from 'react-dom';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App />, document.getElementById('app'));

package.json 片段

"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 8001
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}

唯一的问题是输出在浏览器上未显示

命令提示符 COMMAND PROMPT AFTER "npm start"

浏览器 output not displaying

最佳答案

在根文件夹中添加一个 .babelrc 文件,内容如下:

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

并且 package.json 预计包含以下依赖项:

  "devDependencies": {
"@babel/core": "^7.4.0",
"@babel/preset-env": "^7.4.2",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
}

更新

同时将 webpack.config.js 更新为:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
entry: "./main.js",
output: {
path: path.join(__dirname, "/bundle"),
filename: "index_bundle.js"
},
devServer: {
inline: true,
port: 8001
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html"
})
]
};

关于javascript - ReactJS代码编译成功,但未在浏览器上打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57051680/

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