Search code examples
javascriptamdwebpack

Using webpack to process an AMD library with external dependencies


I have a library written in AMD style that can be used with RequireJS. jquery and jquery-ui are assumed to be provided by the user of the library. Say it looks like this:

// main-lib.js
define(['jquery', './aux-lib.js'], function ($) { ..(1).. });

// aux-lib.js
define(['jquery', 'jquery-ui'], function ($) { ..(2).. });

I'm trying to figure out how webpack works. For example, say I want to bundle these files into a single AMD style library file that still assumes jquery and jquery-ui from the outside:

// out.js
define(['jquery', 'jquery-ui'], function ($) { ..(1)..(2).. } );

How is this accomplished?

When I run webpack with main-lib.js as entry-point, it will complain that it can't find jquery and jquery-ui. If I configure the correct paths with resolve.alias, it bundles jquery and jquery-ui into out.js, which is not what I want. I tried using output.externals to no avail.


Solution

  • This was a pretty simple, stupid mistake on my part. The relevant field is not output.externals, but simply externals. See here. The other two relevant fields introduced there are inside output, but externals is not.

    PS: externals can also be an array. Here is my current configuration:

    {
        entry: './main-lib.js',
        output: {
            path: './',
            filename: 'out.js',
            libraryTarget: 'amd'
        },
        externals: ['jquery', 'jquery-ui']
    }
    

    It's working quite nicely.