2017-09-27 95 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$/ 
     }] 
    } 
} 

我也移除了您的裝載機陣列最後一個空屬性。

祝你好運!