在Webpack中将库配置为外部库无法与将UMD作为库目标一起使用

janis91

我在最近的两天内尝试了此操作,但无法按预期工作:我想构建自己的JavaScript库,并在一个现有的命名空间(在这种情况下为“ OCA”)下注册它。正如您可能理解的那样,我不想被迫没有诸如通过打字稿或模块进行类型安全之类的现代方法。

因此,我使用webpack 2和将libraryTarget: umd输出注册到“ OCA.Ocr”下(我的库名为“ Ocr”)。这可以按预期工作,但是到了要使用例如underscorejs的地步,因为它也应该在应交付给库的应用程序中全局使用,但我无法使其正常工作。我遵循了webpack配置文档,并说外部配置选项应该是可行的方法:

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

我按照指南的建议使用它,但是它不起作用:

/* 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;

}

我的app.ts文件使用下划线库(例如_.defer方法,当然不一定总是最好使用的方法)如下所示:

import _ from 'underscore';

export class App {

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

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

我将它包含在应用程序中,还检查了在我的库被浏览器加载之前,underscorejs库是否已加载,但是控制台输出仍然指出:

TypeError:underscore_1.default未定义

编译后的输出如下(也许会有所帮助):

(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();


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

有谁知道这是如何工作的以及我将要做什么?我完全迷失了,现在希望您的帮助。

顺便说一句:对我也不起作用。

史蒂芬·斯潘金(Steven Spungin)

您在这里有2个选项。我建议选择#1。

实际上,如果您使用UMD并计划支持node(除了commonjs,amd和浏览器之外),请务必设置globalObject: 'this'

设置output.globalObjectthis,然后使用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

以库为目标时,尤其是在libraryTarget为'umd'时,此选项指示将使用哪个全局对象来安装库。要使UMD构建在浏览器和Node.js上均可用,请将output.globalObject选项设置为'this'。

使用externals.var代替externals.root


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

这是一种解决方法,不需要设置globalObject: 'this'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将库与emscripten一起使用

如何配置 IntelliJ 以将 SVN 与 CVS、GIT 等一起显示为存储库选项?

在Unity中将通用存储库与TEntity一起使用

通过Proguard获得警告(与外部库一起使用)

内联如何与外部库一起使用?(迅速)

在Visual Studio 2010中将MySQL数据库与Entity Framework一起使用

将本地npm库与es6,babel和webpack一起使用

将外部库与Formik一起使用Rollup.JS不尊重命名的导出

如何将Android Room与外部库提供的POJO一起使用?

我可以将GitLab与外部/远程存储库一起使用吗?

HTTPS4组件配置,用于将SSLcontext与密钥库文件一起使用,仍然无法找到到请求目标的有效证书路径

无法使用“from”引用与 pip 一起安装的库

Javascript无法与jquery库1.9.1一起使用

Intellij 无法导入 Java 库以与 Kotlin 一起使用

在Flutter中将Chopper网络库与flutter_bloc库一起使用

将Java库与Scala保留字一起使用

将库(Plyr)与指令和AngularJS一起使用

如何将Seaborn库与pydatatable一起使用?

将Eigen库与cppyy一起使用

将Hystrix与Spring数据存储库一起使用

将WebServiceTemplate与密钥库一起使用

将视图模型与存储库模式一起使用

将SpringSessionBackedSessionRegistry与Redis会话存储库一起使用

将GDB与Eigen C ++库一起使用

将recyclerview与数据库一起使用

将 arrayList 与数据库一起使用?

将Nininject MVC与类库一起使用

将PayPal IPN与iOS PayPal库一起使用

将GreenSock JS库与Webstorm一起使用