webpack.js.org icon indicating copy to clipboard operation
webpack.js.org copied to clipboard

How to import script from externals in another external script?

Open Ajax-ua opened this issue 1 year ago • 0 comments

I have to use externals for some lazy loaded chunks of my app (it's a requirement of the environment in which the app is being developed). Script loading is made manually on specific user actions. Externals type is script and there is no problems to use it independently in different parts of the app.

webpack.config

{  
  ...
  output: {
    path: path.resolve(__dirname, env.home + '/dist'),
    filename: '[name].bundle.js',
    chunkFilename: '[name].chunk.js',
    clean: true,
    library: {
      type: 'umd2',
    },
  },
  externalsType: 'script',
  externals: {
    ['a.js']: ['/dist/a.bundle.js', 'a'],
    ['b.js']: ['/assets/b.js', 'b'],
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: [
              [
                "@babel/plugin-transform-runtime",
                {
                  "regenerator": true,
                  "useESModules": false,
                },
              ],
            ],
          },
        },
      },
    ],
  },
  ...
}

main.bundle.js

...
function userAction() {
  import('a.js').then(res => {
    ...
  });
}
function anotherUserAction() {
  import('b.js').then(res => {
    ...
  });
}
...

But if the script from externals is imported in another script from externals when the browser tries to load the script I get the error: ScriptExternalLoadError: Loading script failed. a.bundle.js

import * as b from 'b.js';
...

How can I make it work keeping a and b as the externals?

Ajax-ua avatar Nov 16 '22 11:11 Ajax-ua