简体   繁体   English

为什么我无法在Webpack加载的节点8.1.0 AWS Lambda函数中访问导出的类的函数

[英]Why can't I access exported class's function in Webpack-ed node 8.1.0 AWS Lambda function

I'm writing an AWS Lambda function using the Node 8.1.0 runtime. 我正在使用Node 8.1.0运行时编写一个AWS Lambda函数。 My index.js looks like this: 我的index.js看起来像这样:

import MyCustomClass from 'my-custom-class';

exports.handler = async(event) => {
  console.log('MyCustomClass.getDummy()', MyCustomClass.getDummy());
  return null;
};

My my-custom-class.js looks like this: 我的my-custom-class.js看起来像这样:

export default class MyCustomClass {
  constructor() {
    this.dummy = 'Hello World'
  }

  getDummy() {
    return this.dummy;
  }
}

I'm bundling with the following webpack config: 我捆绑了以下webpack配置:

var path = require('path');

module.exports = {
  mode: 'development',
  entry: [
    path.join(__dirname, 'src/index.js')
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    libraryTarget: 'commonjs'
  },
  target: 'node',
  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules']
  }
};

When I bundle my function I don't get any errors, and what I see in my resulting bundle.js looks good, but I get the following error in AWS: TypeError: my_custom_class__WEBPACK_IMPORTED_MODULE_0__.default.getDummy is not a function 当我捆绑函数时,我没有得到任何错误,并且在生成的bundle.js中看到的内容看起来不错,但是在AWS中却收到以下错误:TypeError:my_custom_class__WEBPACK_IMPORTED_MODULE_0 __。default.getDummy不是一个函数

You are trying to access a method in a static way, however, the method is not static . 您正在尝试以static方式访问方法,但是该方法不是static

Use the new keyword to create an instance of the class then you can use the method. 使用new关键字创建类的实例,然后可以使用方法。

exports.handler = async(event) => {
  let myCustomClass = new MyCustomClass;
  console.log('MyCustomClass.getDummy()', myCustomClass.getDummy());
  return null;
};

Another option, is to make the method static, but then you will need to make the property that the method references static as well. 另一个选择是使该方法静态化,但是您还需要使该方法引用的属性也静态化。

exports.handler = async(event) => {
  console.log('MyCustomClass.getDummy()', MyCustomClass.getDummy());
  return null;
}

export default class MyCustomClass {
  static getDummy() {
    return this.dummy;
  }
}
MyCustomClass.dummy = 'Hello World'

Note: I do not recommend mixing es6 with es5 , either stick with export xxx or exports.xxx 注:我不建议混合es6es5 ,要么坚持export xxxexports.xxx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM