【发布时间】:2020-08-26 11:14:11
【问题描述】:
我正在尝试使用 React 实现我的 node.js 服务器。我已经用 react 配置了 webpack,但我不知道如何在我的服务器上启动它。是否可以不使用 express.js? 现在它只是渲染 index.html 而没有其他存在于 react 中的页面。 谢谢!
Webpack.config
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');
module.exports = {
entry: "./src/index.js",
output: {
path: path.join(__dirname, 'dist'),
filename: "main.js"
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env','@babel/preset-react'],
}
}
},
{
test: /\.scss$/,
use: ['style-loader','css-loader','sass-loader']
}
]
}
};
server.js
const http = require("http");
const path = require("path");
const fs = require("fs");
const indexFile = path.join(__dirname, "../src", "index.html");
const server = http.createServer((req, res) => {
if (req.url === "/") {
fs.readFile(indexFile, "utf-8", (err, content) => {
if (err) {
throw err;
}
res.end(content);
});
}
});
server.listen(3000, () => {
console.log("server is running");
});
package.json
"scripts": {
"dev": " webpack --mode development && node server/server.js",
"build": "webpack --mode production"
},
【问题讨论】:
标签: javascript node.js reactjs webpack localhost