将第三方js文件导入到Angular TypeScript项目中

7

在我使用Angular的经验中,我被迫使用了四种不同的方式来包含第三方库poliglot.js(用于多语言)。

因此,为了能够在我的Lang类中使用new Polyglot(...)

export class Lang
{
    ...
    constructor() {

        this.polyglot = new Polyglot({ locale: 'en' });
        ...        
    }
    ...
}

我会使用以下四种方法:

A. 在我相当老的(2016年)angular2项目中(基于框架angular2-webpack-starter),我采用以下解决方案(由于新版angular项目缺乏require指令,该解决方案目前不可用):

var Polyglot = require('../../../node_modules/node-polyglot/build/polyglot.min.js');

B. 在我的下一个项目中,使用基于 angular2-webpack-starter 的 angular4 技术:

import Polyglot from '../../../node_modules/node-polyglot/build/polyglot.min.js'; 

C. 最近我在 Laravel 项目中嵌入了基于 angular-cli 的 Angular5 项目。

import * as Polyglot from '../../../node_modules/node-polyglot/build/polyglot.min.js';

D. 我还发现了第四种解决方案,适用于我的一些旧的基于 jQuery 的 Angular 项目(基于 angular2-webpack-starter),而且网上有很多人提到这个解决方案。但我使用Polyglot示例将其记录下来:

import '../../../node_modules/node-polyglot/build/polyglot.min.js';
declare var Polyglot: any;

// declare var $:any   // this is for jquery (as example)

问题是:这四个解决方案之间有什么区别,它们是如何工作的?为什么在一些项目中一个解决方案有效而其他解决方案无效?


这取决于您如何设置您的构建。 - SLaks
@SLaks - 你能否提供更多细节(以及构建设置示例)?到底有什么区别呢? - Kamil Kiełczewski
你使用Webpack吗?Browserify?还是其他什么工具? - SLaks
@SLaks webpack(因为angular-cli,angular-webpack-starter使用它)。我还想强调一下,polyglot.js库不会改变。 - Kamil Kiełczewski
1个回答

9

让我们来分解一下:

A:仍然适用于任何版本的Angular,只需在使用之前声明require即可。

declare const require: any;
const Polyglot = require('../../../node_modules/node-polyglot/build/polyglot.min.js');

B: 点 A 使用 CommonJS 模块系统来加载依赖项,其他点使用 ES6 动态导入系统(默认情况下可以像 commonjs 模块系统一样使用 webpack)。如果库公开了模块,则可以直接导入 Polyglot。

export class Polyglot {}

C: 如果 Polyglot 有多个成员,您都想使用,您可以通过编写以下方式导入 Polyglot 的所有成员

import * as Polyglot from '../../../node_modules/node-polyglot/build/polyglot.min.js';

D: Polyglot被导入但未绑定到任何变量。但是,Polyglot公开了一个全局对象,您在声明变量之前无法访问该对象,直到您声明的变量可用为止。
请参见mdn reference以获得更好的解释。
根据您使用的构建系统,没有答案可以保证一定有效,但我的解决方案A应该在每个webpack构建中都有效,B和C也是如此。友情提示,如果没有其他方法来导入/使用模块,则A和D不是最佳解决方案,只能用于必要时。
编辑: ES6标准仅描述了模块的内容、包含的内容、模块应如何导出导入等。
因为ES6不是一个库或类似的东西,所以它没有办法处理这些“旧”的模块。 CommonJS也只是一种标准,由Node.js实现,你可以通过require('module')导入模块。
Webpack可以帮助你处理这两种模块系统,因为它们都被实现了。 如果你创建一个空项目并通过webpack --env development构建,你可以看到Webpack如何处理不同的模块。Webpack编译你的代码并添加自己的处理ESModules或CommonJS模块的方式。根据他们找到的模块,它们将调用不同的方法。我添加了一个编译代码的示例。

/******/ (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;
/******/
/******/  // define getter function for harmony exports
/******/  __webpack_require__.d = function(exports, name, getter) {
/******/   if(!__webpack_require__.o(exports, name)) {
/******/    Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/   }
/******/  };
/******/
/******/  // define __esModule on exports
/******/  __webpack_require__.r = function(exports) {
/******/   if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/    Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/   }
/******/   Object.defineProperty(exports, '__esModule', { value: true });
/******/  };
/******/
/******/  // create a fake namespace object
/******/  // mode & 1: value is a module id, require it
/******/  // mode & 2: merge all properties of value into the ns
/******/  // mode & 4: return value when already ns object
/******/  // mode & 8|1: behave like require
/******/  __webpack_require__.t = function(value, mode) {
/******/   if(mode & 1) value = __webpack_require__(value);
/******/   if(mode & 8) return value;
/******/   if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/   var ns = Object.create(null);
/******/   __webpack_require__.r(ns);
/******/   Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/   if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/   return ns;
/******/  };
/******/
/******/  // 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 = "./main.js");
/******/ })
/************************************************************************/
/******/ ({

/***/ "./esmodule.js":
/*!*********************!*\
  !*** ./esmodule.js ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n  value: true\n});\nexports.default = void 0;\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar MyClass = function MyClass() {\n  _classCallCheck(this, MyClass);\n\n  console.log('test');\n};\n\nexports.default = MyClass;\n\n//# sourceURL=webpack:///./esmodule.js?");

/***/ }),

/***/ "./main.js":
/*!*****************!*\
  !*** ./main.js ***!
  \*****************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval("\n\nvar test = _interopRequireWildcard(__webpack_require__(/*! ./esmodule.js */ \"./esmodule.js\"));\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }\n\n__webpack_require__(/*! ./module */ \"./module.js\");\n\n//# sourceURL=webpack:///./main.js?");

/***/ }),

/***/ "./module.js":
/*!*******************!*\
  !*** ./module.js ***!
  \*******************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
eval("\n\nmodule.exports = {\n  myFunction: function myFunction() {\n    console.log('Test');\n  }\n};\n\n//# sourceURL=webpack:///./module.js?");

/***/ })

/******/ });

//// main.js
require('./module')
import * as test from './esmodule.js';
//// esmodule.js
export default class MyClass{
    constructor(){
        console.log('test')
    }
}
//// module.js
module.exports = {
    myFunction: function () {
        console.log('Test')
    }
}

你可以看到Webpack创建了一个自执行函数,该函数获取所有已创建的模块及其{id(pathToFile):function(module, exports, __webpack_require__)}。在2种不同的模块类型(ESModule,Module --> CommonJS)中,你可以看到Webpack以不同的方式处理这些类型。如果您想要更深入地了解,请让我再次编辑我的帖子。

如果你使用 npm 并查看 polyglot.js(min)中的内容,你会发现其中没有 export class - 那么为什么 B 和 C 在某些项目中可以工作? - Kamil Kiełczewski
编译后的代码位于/node_modules/node-polyglot/build/目录下(包括polyglot.js和它的压缩版本polyglot.min.js)- ES6如何处理这些“旧”的模块导出? - Kamil Kiełczewski
1
我对这个答案有些满意 - 仍然不知道ES6如何处理这些“旧”的模块导出(你只是给出了你的猜测)。你将获得奖励,但是除非你在这一点上进一步阐述你的答案,否则我不会将此问题标记为已接受。 - Kamil Kiełczewski
我会研究官方文档并编辑我的答案,但是我可以说ES6什么也不做,因为它只是定义模块应该长什么样子以及如何处理它们。 - Sven
我能做的唯一更多的事情,就是解释webpack代码的工作原理,如果这正是你所需要的。 - Sven
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接