2017-09-27 182 views
1

我想用Weback来构建一个简单的lambda nodejs函数hello world。webpack&aws lambda

exports.handler = (event, context, callback) => { 
    callback(null, 'Hello from Lambda'); 
}; 

该函数在lambda中工作,处理器“index.handler”在aws lambda配置页面中配置。

上述的Webpack生成的代码不起作用。该函数在模块'index'上抛出错误“Handler'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函数的人?

任何帮助表示赞赏。

+0

为什么你的处理程序名为“index.handler”,但你的webpack入口点是“autotag.js”?你能否包含你的目录结构来显示文件的相对位置? – dashmug

+0

一个简单的解决方案是简单地编写一个附加'exports.handler = global.handler;'的脚本到最后一个bundle的末尾。我通常编写'npm run bundle'来首先运行webpack,然后运行一个脚本将它附加到bundle的末尾。 – kevin628

+0

感谢您的关注。 Webpack在dist文件夹中生成autotag.js文件。然后将代码复制到AWS Lambda以创建该文件。对于任何内联代码,处理程序是“index.handler”。我也尝试使用包含autotag.js的zip文件以及node_modules,但是存在相同的错误。在这种情况下,处理程序是autotag.hander。 – CalmCloud

回答

1

我复制了你的错误,发现有一点变化,使它运行。

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

你需要告诉的WebPack该代码将在CommonJS的环境中运行,并出口对象它将附加入口点(为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$/ 
     }] 
    } 
} 

我也移除了您的装载机阵列最后一个空属性。

祝你好运!