standard-things / esm

Tomorrow's ECMAScript modules today!
Other
5.26k stars 146 forks source link

Usage example with the Serverless Framework #818

Closed Vadorequest closed 5 years ago

Vadorequest commented 5 years ago

I'm looking for a basica example of how to use ESM with the https://serverless.com/ framework.

I tried to look out to see if there was other related issue, found this one but wasn't really useful. https://github.com/standard-things/esm/issues/586

From my first experience with ESM a few months ago -which was awesome-, I'm very interested in using it with serverless, because I'm really tired of having to re-learn everything that's changed in babel/webpack since the last time I had to setup a project (so much time wasted)

I believe that loading a file, that loads esm itself nd then loads a ES7 .js file should just work, I'm gonna give it a try, but any direction would be appreciated.

Vadorequest commented 5 years ago

Indeed, it works just fine:

functions:
  status:
    handler: src/functions/_status.handler
    events:
      - http:
          method: GET
          path: /status
          cors: true

/src/functions/_status.js

// XXX See https://github.com/standard-things/esm#getting-started
// Set options as a parameter, environment variable, or rc file.
require = require('esm')(module);
module.exports = require('./status.js');

/src/functions/status.js

import RavenLambdaWrapper from 'serverless-sentry-lib';
import Raven from 'raven';
import moment from 'moment';

export const handler = RavenLambdaWrapper.handler(Raven, async (event, context) => {
  return {
    body: JSON.stringify({
      status: 'OK',
      processNodeEnv: process.env.NODE_ENV,
      time: moment().toISOString(),
      appName: process.env.APP_NAME,
      release: process.env.GIT_COMMIT_VERSION,
      releasedAt: process.env.DEPLOY_TIME,
      version: process.env.npm_package_version,
      nodejs: process.version,
    })
  };
});

Output:

{
"status": "OK",
"processNodeEnv": "staging",
"time": "2019-06-16T16:25:36.342Z",
"nodejs": "v8.10.0"
}

With a couple limitations:

jdalton commented 5 years ago

Thank you for this @Vadorequest!

I believe you can mix some hot reloading in if you use something like node-hot-loader.

Vadorequest commented 5 years ago

A basic nodemon worked fine actually. (small app)

But I eventually got back to traditional Webpack (😢) because Jest wasn't supported by ESM yet.