node.jswebpackaws-lambdanode-modulesmjs

Unable to build lambda with webpack and fontkit


I am trying to add PDF generation to my mailer script implemented as AWS Lambda function. It is working fine locally, etc. When I am packing it with webpack 4, it does not work.

My webpack config is below:

'use strict';

const webpack = require('webpack');
const path = require('path');

module.exports = {
  node: {
    __dirname: true
  },
  entry: './src/index.js',
  output: {
    library: 'mylib',
    libraryTarget: 'commonjs2'
  },
  resolve: {
    extensions: ['.json', '.jsx', '.js', '.mjs'],
    alias: {
      'tiny-lru': path.join(
        process.cwd(),
        './node_modules/tiny-lru/lib/tiny-lru.cjs.js'
      ),
      // pdfkit: 'pdfkit/js/pdfkit.js',
      'unicode-properties': 'unicode-properties/unicode-properties.cjs.js'
    }
  },
  target: 'node',
  optimization: {
    minimize: true
  },
  externals: [
    'aws-sdk',
    'pino-pretty',
    'uglify-es',
    'uglify-es/package.json'
  ],
  plugins: [
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
    new webpack.IgnorePlugin(/^pg-native$/)
  ],
  module: {
    rules: [
      {
        test: /unicode-properties[\/\\]unicode-properties/,
        loader: 'transform-loader?brfs'
      },
      //     { test: /pdfkit[/\\]js[/\\]/, loader: 'transform-loader?brfs' },
      { test: /fontkit[\/\\]index.js$/, loader: 'transform-loader?brfs' },
      //     {
      //       test: /linebreak[\/\\]src[\/\\]linebreaker.js/,
      //       loader: 'transform-loader?brfs'
      //     }
      { test: /\.mjs$/, include: /node_modules/, type: "javascript/auto"}
    ]
  }
};

When I am building this thing, it errs with:

ERROR in ./node_modules/fontkit/dist/module.mjs 7463:26
Module parse failed: Unexpected token (7463:26)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

The way I was able to build for lambda is by making fontkit external. It compiles, but does not work. As expected, it errs at runtime with: Runtime.ImportModuleError: Error: Cannot find module 'fontkit'".

I tried { test: /fontkit[\/\\]index.js$/, loader: 'transform-loader?brfs' } as well as { test: /\.mjs$/, include: /node_modules/, type: "javascript/auto"}, and it made no difference so far.

Any recommendations?


Solution

  • I ended-up adding the below:

    layers:
      Pdfkit:
        name: Pdfkit
        compatibleRuntimes:
          - nodejs16.x
        description: Required for Pdfkit
        package:
          artifact: layer/pdfkit-layer.zip
    custom:
    

    and installing everything in a zip there, while marking these libraries as external in webpack config.