我正在尝试使用 Webback 构建一个简单的 lambda nodejs 函数 hello world。
exports.handler = (event, context, callback) => {
callback(null, 'Hello from Lambda');
};
此函数在 lambda 中使用在 aws lambda 配置页面中配置的处理程序“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 函数吗?
感谢任何帮助。
最佳答案
我已经复制了您的错误,并发现了一个细微的变化以使其运行。
在 webpack.config.js 中,我添加了 libraryTarget: 'commonjs' 到输出对象。
您需要告诉 webpack 此代码将在 commonjs 环境中运行,并且它将入口点附加到 exports 对象(正如 Lambda 所期望的,并且您的变通方法是手动执行的)
这是 Webpack 指南中的相关部分:
libraryTarget: "commonjs" - The return value of your entry point will be assigned to the exports object using the output.library value. As the name implies, this is used in CommonJS environments.
这是特定 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$/
}]
}
}
我还删除了加载程序数组中的最后一个空属性。
祝你好运!
关于node.js - webpack 和 aws lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46446377/