Search code examples
javascriptwebpackrequirejsamdwebpack-2

Is there a way to load AMD modules from modules compiled with Webpack (at runtime over the network)?


Is there a way to load AMD modules from modules compiled with Webpack (at runtime over the network)?

f.e., I have

import Blah from './Blah'
import AmdModule from './AmdModule'

where AmdModule is an AMD module that has a single define() call in it. I don't want webpack to compile that file and I don't want webpack to include it in the bundle. Maybe that file doesn't even exist at compile time, but will exist on the asset server. I want that file to be loaded at runtime, over the network.

Is there some way to make Webpack do that kind of stuff? I was thinking maybe to import that file with RequireJS, but then it breaks Webpack modules because there's no way to wait for the module to load and then export something asynchronously in webpack modules.

Ideally, I'd like for webpack to wait for those files to be loaded from the network before executing the module that needs it.

Is something like this possible?

As requirement, the to-be-loaded-by-network file can not be compiled, it must remain an AMD define() module loaded over the network, untouched, no source map needed.


Solution

  • Webpack can specify different methods ( AMD and CommonJs ) to load code on demand.

    Here is an extract from the webpack guide :

    To clarify a common misunderstanding: Code Splitting is not just about extracting common code into a shared chunk. The more notable feature is that Code Splitting can be used to split code into an on demand loaded chunk.

    Regarding how you can configure how externals are exposed you can look at this sample ( webpack/examples/externals ) :

    module.exports = {
        output: {
            libraryTarget: "umd"
        },
        externals: [
            "add",
            {
                "subtract": {
                    root: "subtract",
                    commonjs2: "./subtract",
                    commonjs: ["./math", "subtract"],
                    amd: "subtract"
                }
            }
        ]
    }