gpt4 book ai didi

javascript - 使用快速服务器在 React 应用程序中热重载

转载 作者:行者123 更新时间:2023-12-05 07:06:38 27 4
gpt4 key购买 nike

截至目前,我已经为 MERN 应用程序设置了样板,该应用程序在后端有一个快速服务器并在前端使用react。我打算在我的应用程序中设置热重载——每当 react 代码发生任何变化时,无需刷新整个应用程序 (HMR)。

我安装了 webpack-dev-serverHotModuleReplacementPlugin。我还尝试在 package.jsonwebpack 脚本中使用 --hot。如果我运行 npm run webpack,代码会编译,服务器会在 localhost:8080 上启动。它给了我这样的东西,这不是我真正想要的。我不知道它看起来像是在向我显示根目录。

enter image description here

另一方面,如果我运行 npm start,服务器会启动并显示 react 组件,这正是我想要的,但带有热重载。现在,我必须刷新页面才能看到更改。

enter image description here

所以,我想了解到底发生了什么?有没有办法在我输入 npm start 时添加热重载?



客户端/index.js

import React from "react"
import ReactDOM from "react-dom"
import App from "./containers/App"

ReactDOM.render(<App />, document.getElementById("root"))


客户端/容器/App.js

class App extends Component {
render() {
return (
<div>
<Router>
<Switch>
<Route exact path="/" component={HomePage} />
</Switch>
</Router>
</div>
)
}
}

export default App


client/components/HomePage.js

const HomePage = () => {
return (
<div>
<h1>React HomePage</h1>
</div>
)
}

export default HomePage


routes/index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/*', function(req, res, next) {
res.render('index', { title: 'Travel Forum' });
});

module.exports = router;


views/index.ejs

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<div id="root"></div>
<script src="/static/bundle.js"></script>
</body>
</html>


package.json

  "scripts": {
"start": "NODE_ENV=development nodemon ./bin/www",
"webpack": "webpack-dev-server --config ./webpack.config.js --mode development --hot"
},


webpack.config.js

/* eslint-disable */
var webpack = require("webpack")
var path = require("path")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")

module.exports = {
mode: "development",
devtool: "inline-source-map",
entry: ["./client/index.js"],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: { loader: "babel-loader" },
},
{
test: /\.(scss|css)$/,
use: [
{ loader: MiniCssExtractPlugin.loader },
{
loader: "css-loader",
},
{ loader: "sass-loader" },
],
},
{
test: /\.(png|jpg|gif|jpeg)$/,
use: [
{
loader: "file-loader",
options: {},
},
],
},
],
},
resolve: {
extensions: [".js", ".jsx"],
},
output: {
filename: "bundle.js",
path: __dirname + "/dist/bundle/",
publicPath: "/static/",
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("development"),
},
}),
new MiniCssExtractPlugin({
filename: "bundle.css",
}),
],
}


app.js

const createError = require("http-errors")
const express = require("express")
const bodyParser = require("body-parser")
const path = require("path")
const cookieParser = require("cookie-parser")
const logger = require("morgan")
const mongoose = require("mongoose")

const indexRouter = require("./routes/index")
const userRouter = require("./routes/users")

const app = express()

// view engine setup
app.set("views", path.join(__dirname, "views"))
app.set("view engine", "ejs")

app.use(logger("dev"))
app.use(express.json())
app.use(bodyParser.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, "public")))

if (process.env.NODE_ENV === "development") {
const webpack = require("webpack")
const webpackConfig = require("./webpack.config")
const compiler = webpack(webpackConfig)

app.use(
require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: webpackConfig.output.publicPath,
})
)

app.use(require("webpack-hot-middleware")(compiler))
}

mongoose.connect(
"mongodb://localhost:27017/travel-forum",
{ useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false },
function (err) {
if (err) {
console.log("Not connected to the database")
} else {
console.log("Connected to the database")
}
}
)

app.use("/api/v1/users", userRouter)
app.use("/*", indexRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404))
})

// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message
res.locals.error = req.app.get("env") === "development" ? err : {}

// render the error page
res.status(err.status || 500)
res.render("error")
})

module.exports = app


最佳答案

** 我是通过以下方式解决的:**

express 有两个模块,你可以在不刷新浏览器的情况下安装热刷新,它会自动刷新:我把我的配置留给你。

npm i livereload

npm i connect-livereload

const livereload = require('livereload');

const connectLivereload = require('connect-livereload');

const liveReloadServer = livereload.createServer();

liveReloadServer.watch(path.join(__dirname, '..', 'dist', 'frontend'));

const app = express();

app.use(connectLivereload());

enter image description here

请注意,您要监控的文件夹位于 dist/frontend 中。更改您要监视的文件夹以使其工作:要监视后端,我正在使用 NODEMON

livereload 在后端为浏览器打开一个端口以公开更改:连接是如何发生的?这很容易;用“connect-livereload”表达并注入(inject)一个脚本来监视该端口:如果发生变化,浏览器会收到 express 通知,浏览器会为您刷新

我留下的信息尽可能简单以供测试,我不建议这样使用它:要使用它,您必须将开发环境和生产环境分开。我保持简单,以便于理解。

我在这里留下我找到的最相关的链接:我希望它也能有所帮助。

https://bytearcher.com/articles/refresh-changes-browser-express-livereload-nodemon/

关于javascript - 使用快速服务器在 React 应用程序中热重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62403571/

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