动态要求在Webpacked Express服务器内部找不到模块

时间:2018-08-08 18:53:33

标签: node.js webpack requirejs

我有一个非常小的快递申请。基本上一个穷人的服务器少了功能提供者。但是,这不是我在生产中使用的东西,它可以在未打包的模式下工作。但是,在我对该应用程序进行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/'
        }
    }
]

1 个答案:

答案 0 :(得分:0)

我真的尝试了很多东西以及各种模块和插件。最后,他们让我正常工作的唯一方法是使用非常讨厌的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}`)