webpack express 服务器内的动态要求找不到模块

Dynamic require inside a webpacked express server can not find module

我有一个非常小的快递应用程序。基本上是一个穷人的服务器少功能提供者。然而,这不是我在生产中使用的任何东西,它在未打包模式下工作。但是在我对这个应用程序进行 webpack 之后,动态要求总是失败并出现 Error: Cannot find module 异常。但是模块在那里,路径是正确的。

devserver.js:

const express = require('express')
const fs = require('fs')
const resourceMapper = fs.existsSync(__dirname + '/../webpack.config.js') ? require('../webpack.config') : null
const app = express()

// enable express json
app.use(express.json())

// add dynamic lambda functions
app.post('/api/:lambda', function(request, response) {
  const resource = resourceMapper
    ? `${__dirname}/.${resourceMapper[1].entry[request.params.lambda.replace(/^common-/, "").replace(/\.js$/, "")]}`
    : `${__dirname}/${request.params.lambda}`
  const lambda = require(resource)              // <--------- problematic require
  const result = lambda.main(request.body)
  response.status(200).json(result)
});

app.listen(3000)

webpack.conf.js:

module.exports = [
    {
        name: "development-server",
        target: 'node',
        externals: [(require('webpack-node-externals'))()],
        node: {
            __dirname: false,
            __filename: false,
        },
        entry: {
            devserver: "./devserver/server.js",
        },
        output: {
            filename: "./server.js",
            path: __dirname + '/build/node/'
        }
    },
    {
        name: "lambdas",
        target: 'node',
        externals: [(require('webpack-node-externals'))()],
        entry: {
            returns: "./lambdas/returns/src/main/index.js",
            echo: "./lambdas/echo/src/main/echo.js"
        },
        output: {
            library: "[name]",
            libraryTarget: "commonjs2",
            filename: "./common-[name].js",
            path: __dirname + '/build/node/'
        }
    }
]

我确实尝试了很多东西以及各种模块和插件。最后,他们让我工作的唯一方法是使用非常讨厌的 eval 技巧。

const require2 = eval('require')
//[snip]
const lambda = resourceMapper
    ? require(`${__dirname}/.${resourceMapper[1].entry[request.params.lambda.replace(/^common-/, "").replace(/\.js$/, "")]}`)
    : require2(`./${request.params.lambda}`)