2

I'm using Angular 14 and module federation. I want to use import.meta within my remote application to get the absolute path (e.g. starting with "http://") of a resource. In my remote application, I have webpack.config.js configured like so

module.exports = withModuleFederationPlugin({

  name: 'my-app',

  exposes: {
    './home':'./src/app/my-module/products.module.ts'
  },

  shared: {
    ...shareAll({ singleton: true, strictVersion: true, requiredVersion: 'auto' }),
  },

});

Then in my service within the remote application, I try and use import.meta.resolve, like so

@Injectable({
  providedIn: 'root'
})
export class MyService {
    ...
    public init() {
        const absolutePath = import.meta.resolve('./settings.json');

but this throws the compilation error, "Cannot invoke an object which is possibly 'undefined'.". What is the proper way to invoke the "resolve" method in order to get an absolute path of a resource?

Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

0

I think you need to add a parent absolute path as follow :

const absolutePath = await import.meta.resolve('./settings.json', parent);

that resolves a relative specifier in regards to a parent absolute path. parent argument is optional and defaults to the current module absolute path.

Let's say that you have a module main.mjs under the absolute path /home/user/web-app/main.mjs. You also have a module helper.mjs that is located in the same folder as main.mjs. You'd like to get the absolute path to helper.mjs.

Here's how you could do it:

// main.mjs
const resolvedPath = await import.meta.resolve('./helper.mjs');
console.log(resolvedPath); // '/home/user/web-app/helper.mjs'

Executing await import.meta.resolve('./helper.mjs') would resolve ./helper.mjs to /home/user/web-app/helper.mjs absolute path.

If the resolved module doesn't exist, then the function would throw a module not found error.

Here is a very good article that may give you more details : https://dmitripavlutin.com/javascript-import-meta/

Mohamed Chaawa
  • 918
  • 1
  • 9
  • 23