简体   繁体   中英

Webpack externals module name with hyphen

I'm trying to load angular-ui-router in Webpack as an external dependency. The module name is "angular-ui-router". Here's an example:

module.exports = webpackMerge(commonConfig, {
    ...
    externals: {
        'angular': true,
        'angular-ui-router': true
    },
    ...
});

The problem with this is that Webpack creates a module in my app.bundle.js that looks like the following:

/***/ },
/* 1 */
/***/ function(module, exports) {

    module.exports = angular;

/***/ },
/* 2 */
/***/ function(module, exports) {

    module.exports = angular-ui-router;

/***/ }
/******/ ]);

When the browser tries to load the module, it evaluates module.exports = angular-ui-router as an expression, throwing the following error:

Uncaught ReferenceError: ui is not defined

The only fix I have found for this issue is:

module.exports = webpackMerge(commonConfig, {
    ...
    externals: {
        'angular': true,
        'angular-ui-router': 'window["angular-ui-router"]'
    },
    ...
});

This yields the correct result.

Is there a better way?

I was having the same problem, so I got it solved using something like this

module.exports = webpackMerge(commonConfig, {
    ...
    externals: [
      ....
      'angular-ui-router': {
                   commonjs: 'angular-ui-router' 
          }
        }
        ],
    ...
});

When you have externals module name with hyphen use the libraryTarget as umd in the output section. So the app.bundle code would have

require("angular-ui-router") would be used for requireJS and 
root.angularUIRouter = factory(root["angular-ui-router"]) would be used for global variable type.

Bundle code would look like this:

"object" == typeof exports && "object" == typeof module ? 
module.exports = factory(require("angular-ui-router")) : "function" == 
typeof define && define.amd ? define(["angular-ui-router"], factory) : 
"object" == typeof exports ? exports.temp = factory(require("angular-ui-
router")) : root.temp = factory(root["angular-ui-router"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM