nx-aws icon indicating copy to clipboard operation
nx-aws copied to clipboard

NX 15 Webpack and Dynamic Imports

Open dbrody opened this issue 1 year ago • 4 comments

The update to NX 15 in this repo means that it now uses webpack. I see that the builders in this package make use of overwriting the webpack config file. However, I'm now running into issues with some code where I dont see any chunks output from webpack when I expect to the see them.

Specifically, my desire is to have dynamically loaded modules within the lambda functions via await import('@mypackage/api'). However even if I set /* webpackMode: "lazy-once" */ or other options, I still dont see any chunks being created in the dist folder by nx-aws.

Any thoughts?

dbrody avatar Apr 15 '23 18:04 dbrody

Setting tsconfig.json to include compilerOptions.module = "esnext" does create the chunks. Now the issue is if each function exported by sam is in its own folder, all the chunks are in the root. So the lambda function doesnt find the chunks. Using multiple configurations from webpack doesnt work with the implementation of "@nrwl/webpack" it seems.

Any workarounds to get chunks properly included in the export of each function?

dbrody avatar Apr 15 '23 20:04 dbrody

Hi @dbrody, this is not something that I've done, so I don't have any ready advice. Do you have an demo repo I could have a play with?

studds avatar May 01 '23 23:05 studds

@studds Unfortunately I don't. I sort of found a way around this where I have webpack copy files and rewrite paths etc between apps and for each lambda function within the NX project. When I have time to dig in more I can try to isolate this more for you.

Webpack compresses all files with paths into a single file or a few files. So all chunks are relative to the base of the app. So if a lambda function CodeUri is not the base of the app, the exported code will not have access to these chunks in the main app. I worked around this by having webpack copy the files to each folder relevant for each lambda function. I also have it rewrite paths to properly find them.

dbrody avatar May 02 '23 02:05 dbrody

The best way to reproduce this would be to have a nx-aws project defining two serverless functions each in their own CodeUri folder (CodeUri: functions/func_a and CodeUri: functions/func_b). And give the exported function files common code they depend on so it create vendor/chunk file in the main.

For example:

  • shared.ts
  • /functions
    • func_common.ts
    • /func_a
      • index.ts
    • /func_b
      • index.ts

I think the output would be:

  • vendors.js
  • {any chunks}.js
  • /functions
    • /func_a
      • index.js
    • /func_b
      • index.js

But the function index.js would reference the chunks in the main app. Which the exported lambda function would not since it is just the folder itself being combined.

Hopefully that makes sense.

dbrody avatar May 02 '23 02:05 dbrody