node.jswebpackimportmodulewebpack-4

Using Browser Imports with webpack


I am using webpack to compile a plugin for a shopify theme that leverages browser based modules <script type ='module'...></script> allowing you to import universal functionality with import {Drawer} from '/theme.js' this works great except that I am not including the theme.js in my webpack so I get errors:

ERROR in external "/theme.js"
The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script

Solution 1

Using a dynamic import with webpackIgnore:true seems to work like so:

import(/* webpackIgnore: true */ "/theme.js").then(() => {
...
});

but this is not ideal as there are other utilities and things that we'd like to import in other places in the code where we can't use dynamic imports.

Solution 2

I tried using the IgnorePlugin to match the browser imports

new IgnorePlugin({
          resourceRegExp: /^\/theme.js$/
      })

which works to remove the initial error but still has a runtime error of:

Error: Cannot find module "theme.js"

Is there a better way to mix webpack with browser modules or is this just not the right approach?


Solution

  • Seems like the key is to use externalsType: 'module' along with experiments.outputModule so my final webpack config has this in it:

    ...
        experiments: {
          outputModule: true,
        },
        externalsType: 'module',
        externals: {
            'static.theme.js': 'https://cdn.shopify.com/.../static.theme.js'
        },
    ...