Webpack已编译但不运行后端代码

时间:2018-11-29 15:52:58

标签: javascript reactjs webpack

我正在使用Webpack将项目绑定到SDK中。该项目使用React作为客户端,并使用Node.js + express作为后端。因此,我正在尝试将前端和后端代码捆绑在一起。

到目前为止我做了什么: 我在没有webpack的情况下启动了项目。因此,我的代码被确认可以正常工作。我能够将它们都捆绑到webpack中而不会引发错误。当我转到“ npm run start”时,客户端已正确呈现。但是,服务器端代码似乎没有运行。

我的webpack.config.js:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const nodeExternals = require("webpack-node-externals");

module.exports = [
    {
        /*Client Side bundle*/
        module: {
            rules: [
                {
                    test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader"
                    }
                },
                {
                    test: /\.html$/,
                    use: {
                        loader: "html-loader",
                        options: { minimize: true }
                    }
                },
                {
                    test: /\.css$/,
                    use: [MiniCssExtractPlugin.loader,"css-loader"]
                }
            ]
        },
        plugins: [
            new HtmlWebPackPlugin({
                template: "./public/index.html",
                filename:"./index.html"
            }),
            new MiniCssExtractPlugin({
                filename: "[name].css",
                chunkFilename:"[id].css"
            })
        ]
    },
    {
        /*Config for backend code*/ 
        entry: './src/server/server.js',
        target: 'node',
        output: {
            filename: 'server.js'
        },
        externals: [nodeExternals()]
    }
]

我的package.json:

  "scripts": {
    "start": "webpack-dev-server --open --mode development",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": {
    "/*": {
      "target": "http://localhost:3001"
    }
  },
  "devDependencies": {
    "@babel/core": "^7.1.6",
    "@babel/preset-env": "^7.1.6",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.4",
    "css-loader": "^1.0.1",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "^0.4.4",
    "webpack": "^4.25.1",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.10",
    "webpack-node-externals": "^1.7.2"
  }
}

运行npm run build之后,我的dist文件夹将生成main.jsserver.js。 当我运行npm运行开始。客户端工作正常。但是,当我尝试在node.js处调用端点时。它给了我POST http://localhost:8080/test 404 (Not Found)

我需要帮助的地方: 我正在尝试使用Webpack运行我的后端代码。 我注意到的一件事是,当我不运行项目时,本地主机被设置为localhost:3000。当我通过webpack运行它时,它是localhost:8080。在package.json文件中,我将代理设置为3001,这是问题吗?我应该如何使我的后端代码在webpack中运行?

0 个答案:

没有答案