vue.jswebpack

Migrating from require.context to import.meta.webpackContext


I am trying to migrate my Vue PWA to ESM, replacing all require by import.

But replacing require.context by import.meta.webpackContext gives me the following warning at compile-time:

Critical dependency: Accessing import.meta directly is unsupported (only property access is supported)

And then the following error at run-time:

Uncaught TypeError: {}.webpackContext is not a function

The way I use it is the following:

const icons = import.meta.webpackContext('../components/icon', false, /icon.*\.vue/);

I use webpack 5.75.0

I guess this is the same problem as this and this.


Solution

  • The error from webpack is misleading, the issue comes from the fact that import.meta.webpackContext has other arguments:

    (
      request: string,
      options?: {
        recursive?: boolean;
        regExp?: RegExp;
        include?: RegExp;
        exclude?: RegExp;
        preload?: boolean | number;
        prefetch?: boolean | number;
        chunkName?: string;
        exports?: string | string[][];
        mode?: 'sync' | 'eager' | 'weak' | 'lazy' | 'lazy-once';
      }
    ) => webpack.Context;
    

    So in my case I switched to the following to make it work:

    const icons = import.meta.webpackContext('../components/icon', {recursive: false, regExp: /icon.*\.vue/});