gpt4 book ai didi

node.js - Webpack 生产 process.env.PORT=在服务器编译时未定义(React 应用程序)

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:21 25 4
gpt4 key购买 nike

我的 React 应用程序在开发和生产脚本中编译一切正常,但是,现在我正在 DigitalOcean 上部署,我遇到了 process.env.port 的问题是undefined因此又回到3000而不是预期的端口 80 .

Package.json npm 脚本:


"build": "webpack -p --config webpack.config.production.js &&
cross-env NODE_ENV=production node server/server.js"
Webpack.config.production.js 脚本,其中包含 process.env 的 DefinePlugin():

module.exports = {
entry: {
app: ["./src/scripts/index.js"]
},
output: {
filename: "[name]-bundle.js", path: __dirname, publicPath: "/"
},
devtool: "source-map",
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.(scss|css)$/,
use: [
{loader: "style-loader"}, {
loader: "css-loader"}, {
loader: "sass-loader"}, {
loader: "postcss-loader"}
}
]
},
{
test: /\.(jpg|png|svg)$/,
use: {
loader: "file-loader",
options: {
name: "[path][name].[ext]"
}
}
}
]
},
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
extractSass,
new UglifyJsPlugin({
sourceMap: true,
uglifyOptions: {
output: {
comments: false
}
}
}),
new HtmlWebpackPlugin({
template: "public/index.html",
favicon: "public/assets/img/favicon.ico"
}),
new ExtractTextPlugin({
filename: "styles/styles.css",
allChunks: true
})
]
};

我的 express 服务器文件:

const path = require("path");
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;

let useFolder;

if (process.env.NODE_ENV !== "production") {
useFolder = "/public/";
const webpack = require("webpack");
const config = require("../webpack.config.development");
const compiler = webpack(config);
app.use(
require("webpack-dev-middleware")(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
hot: true
})
);
app.use(
require("webpack-hot-middleware")(compiler, {
log: console.log,
path: "/__webpack_hmr",
heartbeat: 10 * 1000
})
);
} else {
useFolder = "/dist/";
}
app.use(express.static("dist"));

app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, ".." + useFolder + "index.html"));
});

app.listen(port, function(err) {
if (err) {
return console.error(err);
}
console.log("Listening at port: ", port);
});

没有错误,当它在备份端口 3000 上运行时在实时服务器上一切都很好,但我期待端口 80。

我尝试过交换位置 NODE_ENV=production已设置:从 NPM 脚本中删除,并 DefinePlugin() 但也没有成功。

最佳答案

Webpack 默认情况下会打包为 web。这意味着它将用您在 DefinePlugin 中定义的内容替换所有 process.env. 语句。您从未将 PORT 设置为任何内容,因此它将是未定义的。
您有两个选择,要么在 DefinePlugin 中定义 PORT,要么将 webpack 目标更改为 node 并删除 DefinePlugin。这将使 webpack 在运行时使用实际的环境变量。
https://webpack.js.org/concepts/targets/

关于node.js - Webpack 生产 process.env.PORT=在服务器编译时未定义(React 应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49743385/

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