Webpack和AWS Lambda

5
我正在尝试使用Webpack来构建一个简单的lambda nodejs函数-Hello World。
exports.handler = (event, context, callback) => {
    callback(null, 'Hello from Lambda');
};

这个函数在AWS Lambda配置页面中使用handler "index.handler"进行配置。

Webpack生成的代码无法正常工作。该函数会抛出错误:“模块'index'上缺少处理程序'handler'”。看起来模块成为了反义词。

可以通过以下方式更新生成的代码使其正常工作。

global.handler = (event, context, callback) => {
    //async.map(['file1','file2','file3'], console.log, function(err, results){
        // results is now an array of stats for each file
        callback(null, 'Hello from Lambda');
    //});

//add the following at the end.
exports.handler = global.handler;

以下是webpack.config.js文件的内容。
var path = require('path');
module.exports = {
    // Specify the entry point for our app.
    entry: [
        path.join(__dirname, '/src/autotag.js')
    ],
    // Specify the output file containing our bundled code
    output: {
        path: path.join(__dirname, "dist"),
        filename: "autotag.js"
    },
    //target: "node",
    module: {
        /**
         * Tell webpack how to load 'json' files.
         * When webpack encounters a 'require()' statement
         * where a 'json' file is being imported, it will use
         * the json-loader.
         */
        loaders: [{
            test: /\.json$/,
            loaders:
        }]
    }
}

有人使用webpack构建lambda nodejs函数吗?

非常感谢任何帮助。


为什么你的处理程序命名为“index.handler”,但是你在webpack中的入口点是“autotag.js”?你能包含你的目录结构以显示文件的相对位置吗? - Noel Llevares
一个简单的解决方案是编写一个脚本,将exports.handler = global.handler;追加到最终捆绑包的末尾。我通常先运行webpack,然后再运行一个追加脚本来实现它,命令为npm run bundle - kevin628
感谢您的关注。Webpack会在dist文件夹中生成autotag.js文件。然后将代码复制到AWS Lambda中以创建该文件。对于任何内联代码,处理程序为“index.handler”。我还尝试过使用包含根文件夹中的autotag.js和node_modules的zip文件,但是出现了相同的错误。在这种情况下,处理程序为autotag.hander。 - CalmCloud
1个回答

10

我已经重现了您的错误,并找到了一个微小的更改使其运行。

在webpack.config.js中,我向输出对象添加了libraryTarget: 'commonjs'

您需要告诉webpack该代码将在commonjs环境中运行,并将入口点附加到exports对象上(正如Lambda所期望的那样,以及您手动处理的方式)

这是来自Webpack指南的相关部分:

libraryTarget: "commonjs" - 您的入口点的返回值将使用output.library值分配给exports对象。 正如名称所示,这在CommonJS环境中使用。

这是该特定Webpack指南的链接:https://webpack.js.org/configuration/output/#expose-via-object-assignment

这是您的新webpack.config.js:

var path = require('path');
module.exports = {
    // Specify the entry point for our app.
    entry: [
        path.join(__dirname, '/src/autotag.js')
    ],
    // Specify the output file containing our bundled code
    output: {
        path: path.join(__dirname, "dist"),
        filename: "autotag.js",
        libraryTarget: 'commonjs'
    },
    //target: "node",
    module: {
        /**
         * Tell webpack how to load 'json' files.
         * When webpack encounters a 'require()' statement
         * where a 'json' file is being imported, it will use
         * the json-loader.
         */
        loaders: [{
            test: /\.json$/
        }]
    }
}

我还从您的加载器数组中删除了最后一个空属性。

祝你好运!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接