Skip to content

Using Webpack with Modules Dependencies

angelxuanchang edited this page Jan 13, 2018 · 1 revision

Currently, the modules that we use in this project are either:

  1. AMD (our own JS files written in the past when RequireJS was used)
    The value of an AMD-style module is whatever the callback function (i.e., the function passed as the final argument to the define call) returns.

  2. CommonJS (serverside JS and some clientside JS external dependencies)
    The value of a CommonJS-style module is just whatever is assigned to module.exports

  3. Browser globals (some clientside external dependencies that we use, especially the older ones)
    Here, the module's content is exposed as a property on the browser's window object (a global object available in the browser JS environment).

Some inconveniences with using webpack with type (3) dependencies and various solutions:

  1. When a type (3) dependency is processed by webpack, the corresponding optimized webpack code will be executed in a local scope. This may be problematic because some of the type (3) dependencies, especially the older clientside ones, may have been designed with the intention of the JS code executing in a global scope (e.g., from loading JS through a HTML script tag). In a global scope, all variable and function declarations will automatically become properties of the (global) window object. To make these libraries compatible with webpack, you will have to make explicit assignments to the window object in order to expose the behavior of these libraries.

  2. Some of these type (3) dependencies depend on other type (3) dependencies already loaded. e.g., running the dependency bootbox successfully requires the presence of $.fn.modal, which is a function that is appended to the jQuery ($) object by loading of bootstrap, which is dependent on the jQuery dependency already loaded. To make sure the dependencies execute properly, load these dependencies in the correct order. e.g., in AMD, you could do something like: define(['jQuery', 'bootstrap', 'bootbox'], function() { ... });. In CommonJS: require('jQuery'); require('bootstrap'); require('bootbox');

You can also take advantage of the imports loader and webpack's provide plugin for alternative ways of dealing with type (3) modules. See the official webpack documentation for information on these loaders/plugins, and you can take a look at the actual use cases of these loaders/plugins inside of the project webpack config file.

Clone this wiki locally