我正在尝试打包AWS Lambda的代码。 Lambda有各种限制,例如使用Node 6.10,而没有像AWS EB那样的构建步骤。我也在使用NPM模块,因此需要将它们与AWS Lambda处理程序捆绑在一起。
这是我想做的事情:
例如,假设我有一个NPM模块foo
(node_modules/foo/index.js
):
export default { x: 1 };
我有自己的代码('index.js'):
import foo from 'foo';
export const handler = (event, context, callback) => {
console.log(foo); // Will appear in CloudWatch logs
callback(null, 'OK');
};
输出将是这样的('dist / bundle.js'):
var foo = { x: 1 };
exports.handler = function(event, context, callback) {
console.log(foo);
callback(null, 'OK');
};
我应该能够在AWS Lambda上传和运行bundle.js
而无需进一步修改。
如何使用现有的JS工具实现这一目标?
你可以使用serverless和serverless-webpack
然后使用serverless deploy
部署捆绑包
事实证明这是可能的,但它需要一些棘手的配置才能实现。我创建了一个boiler-plate repo供其他人使用。
这是重要的一点......
首先,你需要一个针对Node.js .babelrc
的6.10
:
{
"presets": [
[
"env", {
"targets": {
"node": "6.10"
},
"loose": false,
"spec": true
}
]
]
}
接下来,您需要配置Webpack以生成针对qazxsw poi的qazxsw poi库:
commonjs
请注意,您不希望忽略node
文件夹,因为这会阻止静态链接。
如果您想使用现代JS功能,const path = require('path');
const webpack = require('webpack');
const debug = process.env.NODE_ENV !== 'production';
module.exports = {
context: __dirname,
entry: [ 'babel-polyfill', './index.js' ],
output: {
path: path.join(__dirname, 'out'),
filename: 'index.js',
libraryTarget: 'commonjs'
},
devtool: debug ? 'source-map' : false,
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
babelrc: true,
compact: !debug
}
}
}
],
},
target: 'node',
plugins: [
new webpack.DefinePlugin({ 'global.GENTLY': false })
]
};
插件也很重要。
您的实际处理程序代码应该具有与您在AWS控制台中设置的名称相匹配的命名node_modules
:
babel-polyfill
不要这样做!
export
打包代码时,请确保将export const handler = (event, context, callback) => callback(null, 'OK');
添加到zip的顶层:
// Bad!
export default {
handler: (event, context, callback) => callback(null, 'OK'),
};