简体   繁体   English

在 webpack 中将库配置为外部库不适用于 UMD 作为 libraryTarget

[英]Configuring library as external in webpack does not work with UMD as libraryTarget

I tried this the last two days and I can't get it to work like expected: I want to build my own JavaScript library and register it under an already existing namespace ("OCA" - in this particular case).我在过去两天尝试了这个,但我无法让它像预期的那样工作:我想构建我自己的 JavaScript 库并将它注册到一个已经存在的命名空间(“OCA” - 在这种特殊情况下)。 And as you might understand, I don't want to be forced to go without modern approaches like type safety through typescript or modules.正如您可能理解的那样,我不想被迫放弃现代方法,例如通过打字稿或模块进行类型安全。

Therefore I use webpack 2 and the libraryTarget: umd to register the output under "OCA.Ocr" (my library is named "Ocr").因此,我使用webpack 2libraryTarget: umd在“OCA.Ocr”下注册输出(我的库名为“Ocr”)。 This works like intended, but when it comes to the point that I want to use for example underscorejs , as it will be available globally in the application the library should be also delivered to, I cannot get it to work.这像预期的那样工作,但是当涉及到我想要使用的点时,例如underscorejs ,因为它将在应用程序中全局可用,库也应该交付给,我无法让它工作。 I followed the webpack configuration documentation and it says that the externals configuration option should be the way to go:我遵循了 webpack 配置文档,它说externals配置选项应该是要走的路:

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 like proposed 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 app.ts file which uses the underscore library (for example the _.defer method, which of course is not always the best to use) looks like that:我的app.ts文件使用下划线库(例如_.defer方法,当然并不总是最好使用)看起来像这样:

import _ from 'underscore';

export class App {

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

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

I included it in the application and also checked that the underscorejs library is getting loaded before my lib gets loaded by the browser, but the console output still states:我将它包含在应用程序中,并在浏览器加载我的库之前检查了 underscorejs 库是否已加载,但控制台输出仍然指出:

TypeError: underscore_1.default is undefined类型错误:underscore_1.default 未定义

The compiled output is the following (maybe this helps a little bit):编译后的输出如下(也许这有点帮助):

(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 is working and what I will have to do?有谁知道这是如何工作的以及我必须做什么? I am completely lost and now hoping for your help.我完全迷失了,现在希望得到你的帮助。

Btw: This is also not working for me.顺便说一句: 对我也不起作用。

I have the same issue as you, however, if you set the property var in the libraryTarget option, the variable stops being undefined.我和你有同样的问题,但是,如果你在 libraryTarget 选项中设置属性 var,变量将停止未定义。 Maybe this will help you:也许这会帮助你:

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

You have 2 options here.您在这里有 2 个选择。 I recommend option #1.我推荐选项#1。

In fact, if you use UMD and plan on supporting node (in addition to commonjs, amd, and browser), always set globalObject: 'this'事实上,如果你使用UMD并计划支持node (除了commonjs、amd和browser),总是设置globalObject: 'this'

Set output.globalObject to this , and use externals.root .output.globalObject设置this ,并使用externals.root

const config = {
    output: {
      library: libraryName,
      libraryTarget: "umd",
      globalObject: 'this' // <-- THIS IS THE IMPORTANT LINE FOR UMD+NODE
    },
    externals: {
      underscore: { // UMD
        commonjs: "underscore",
        commonjs2: "underscore",
        amd: "underscore",
        root: "_"
      }
    },
  };

output.globalObject output.globalObject

When targeting a library, especially when the libraryTarget is 'umd', this option indicates what global object will be used to mount the library.当以库为目标时,尤其是当 libraryTarget 为 'umd' 时,此选项指示将使用哪个全局对象来挂载库。 To make UMD build available on both browsers and Node.js, set output.globalObject option to 'this'.要使 UMD 构建在浏览器和 Node.js 上都可用,请将 output.globalObject 选项设置为“this”。

Use externals.var instead of externals.root .使用externals.var而不是externals.root


    externals: {
      underscore: { // UMD
        commonjs: "underscore",
        commonjs2: "underscore",
        amd: "underscore",
        var: "_"
      }
    },

This is a workaround and does not require setting globalObject: 'this'这是一种解决方法,不需要设置globalObject: 'this'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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