How to configure dynamic aliased paths in Nx?
Asked Answered
P

0

7

Background:

I am building an Angular dashboard where I import widgets (Angular modules and components) dynamically (without routing). I achieved this with the help from this great article https://netbasal.com/welcome-to-the-ivy-league-lazy-loading-components-in-angular-v9-e76f0ee2854a.

I am also using Nx and my each widget is a 'NX Angular library'.

Issue:

In my code I'd like to use the path alias set with Nx like like so:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LayoutService {

  loadWidget(name: string) {
    return import(
      /* webpackMode: "lazy" */
      /* webpackPrefetch: true */
      `@dashboard/widget-${name}`
    );
  }
}

But this will result in an error saying module @dashboard not found. However, if I use path in non dynamic way like:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LayoutService {

  loadInfoWidget() {
    return import(
      /* webpackMode: "lazy" */
      /* webpackPrefetch: true */
      `@dashboard/widget-info`
    );
  }
}

Then it all works fine. I understand the issue is that Webpack doesn't pick up the dynamic paths? Is it possible to configure?

Note:

If I use relative paths without alias like so:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class LayoutService {

  loadWidget(name: string) {
    return import(
      /* webpackChunkName: "[request]" */
      /* webpackMode: "lazy" */
      /* webpackPrefetch: true */
      `../../../../widgets/${name}-widget/src/lib/${name}-widget.component`
    );
  }
}

Then it works, but this is a little 'ugly' and not sure yet if it will be causing any other issues. Plus it gives the chunk filename of something like info-widget-src-lib-info-widget-component.js which is also even more 'ugly' than, say 'dashboard-widget-info.js`.

Question:

So, is it possible to configure dynamic aliased paths with NX, typescript and Angular, if so how? Or if you have any better approach tackling this, please share your ideas.

Thank you!

Prismatoid answered 27/12, 2020 at 8:59 Comment(1)
Hey, did you find an answer to this? I have the exact same use case and am trying to find a workaround.Rescript

© 2022 - 2024 — McMap. All rights reserved.