Search code examples
javascriptangularjswebpackcommonjs

What is a good way to include a non-commonJS library to Webpack context?


I want to include an external and non-commonJS library defining an AngularJS module.

What is a proper way to do it since I obviously can't write:

import MyLibrary from 'MyLibraryPath'
angular.module('MyApp', MyLibrary)

EDIT---------

I've just done:

require('path/myLibrary.js'); angular.module('MyApp', 'moduleName');

and it works.

Is it a good practice?


Solution

  • Yes, it is fine if the library doesn't export Angular module's name property. Angular wasn't designed with JS modules in mind and originally promotes angular.module('MyApp', ['moduleName']) module definition style.

    Exporting name from the modules is relatively popular convention, especially because the one can do

    import * as MyLibrary from 'MyLibraryPath';
    

    and use it as

    angular.module('MyApp', [MyLibrary]);
    

    If there is no module export, it can be treated with Webpack exports-loader and

    module: {
        loaders: [
            {
                loader: 'exports-loader',
                test: /path\/myLibrary\.js$/,
                query: '"moduleName"'
            }
        ],
    },
    

    configuration, which essentially adds module.exports = "moduleName"; to the module.

    Use this hack to fix this temporarily if you plan to PR/create an issue for the libraries that don't export name. I wouldn't suggest to make the builds more complicated just to keep the code consistent.