Setting a library as external in webpack does not work with UMD as libraryTarget

I've tried this for the last two days and I can't seem to get it to work as expected: I want to create my own JavaScript library and register it in a preexisting namespace ("OCA" - in this particular case). And as you can imagine, I don't want to be forced to go without modern approaches such as type safety via typescript or modules.

So I use webpack 2 and libraryTarget: umd

for the withdrawal of registration under the "OCA.Ocr" (my library called "Ocr"). This works as intended, but when it comes to what I want to use like underscorejs , since it will be globally available in the application, the library needs to be delivered as well, I can't get it to Work. I have followed the webpack config documentation and it says the externals config option should be as follows:

externals: { // object
    angular: "this angular", // this["angular"]
    react: { // UMD
      commonjs: "react",
      commonjs2: "react",
      amd: "react",
      root: "React"
    }
  }
  // Don't follow/bundle these modules, but request them at runtime from the environment

      

I used it as suggested by the guide, but it doesn't work:

/* global __dirname, require, module*/

const webpack = require("webpack");
const UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
const path = require("path");

module.exports = function (env) {
  let target = env.target;

  let libraryName = ["OCA", "Ocr"];

  let plugins = [];
  let outputFile;

  if (target === "production") {
    plugins.push(new UglifyJsPlugin({ minimize: true }));
  }
  outputFile = "ocr[name].min.js";

  const config = {
    entry: {
      app: __dirname + "/src/app.ts",
      personal: __dirname + "/src/personal.ts"
    },
    output: {
      path: __dirname + "/dist",
      filename: outputFile,
      library: libraryName,
      libraryTarget: "umd",
      umdNamedDefine: true
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          enforce: "pre",
          loader: "tslint-loader",
          options: {
            tsConfigFile: "tsconfig.app.json",
          }
        },
        {
          test: /\.ts?$/,
          loader: "ts-loader",
          exclude: /node_modules/,
          options: {
            configFileName: "tsconfig.app.json"
          }
        }
      ],
    },
    resolve: {
      modules: [path.resolve("./src")],
      extensions: [".ts"],
    },
    externals: {
      underscore: { // UMD
        commonjs: "underscore",
        commonjs2: "underscore",
        amd: "underscore",
        root: "_"
      }
    },
    plugins: plugins,
  };

  return config;

}

      

My file app.ts

that uses the underscore library (for example, a method _.defer

that is of course not always the best) looks like this:

import _ from 'underscore';

export class App {

    constructor() {
        _.defer(() => {
            console.log('test');
        });
    }
}

export let $app: App = new App();

      

I have included it in my app and also verified that the underscorejs library is loaded before my library is loaded by the browser, but the console output still says:

TypeError: underscore_1.default undefined

The compiled output is as follows (maybe it helps a little):

(function webpackUniversalModuleDefinition(root, factory) {
    if(typeof exports === 'object' && typeof module === 'object')
        module.exports = factory(require("underscore"));
    else if(typeof define === 'function' && define.amd)
        define("Ocr", ["underscore"], factory);
    else if(typeof exports === 'object')
        exports["Ocr"] = factory(require("underscore"));
    else
    root["OCA"] = root["OCA"] || {}, root["OCA"]["Ocr"] =     factory(root["_"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
return /******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module,     module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // identity function for calling harmony imports with the correct     context
/******/    __webpack_require__.i = function(value) { return value; };
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony     modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return     Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 2);
    /******/ })
/************************************************************************/
/******/ ([
/* 0 */,
/* 1 */
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE_1__;

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

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var underscore_1 = __webpack_require__(1);
var App = (function () {
    function App() {
        underscore_1.default.defer(function () {
            console.log('test');
        });
    }
    return App;
}());
exports.App = App;
exports.$app = new App();


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

      

Does anyone know how this works and what should I do? I am completely lost and now I hope for your help.

Btw: This doesn't work for me either.

+3


source to share


1 answer


I have the same problem as you, however, if you set the var property in the libraryTarget option, the variable stops being undefined. Maybe this will help you:



externals: {
    "lodash": { 
        var:'_'
    }
}

      

+3


source







All Articles