导入第三方js文件到angular

导入第三方js文件到angular

本文介绍了导入第三方js文件到angular typescript项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我在角度方面的经验,我被迫使用四种不同的方式包含第三方库 poliglot. js (用于多语言).

During my experience in angular I was forced to use four different ways of include 3-rd party library poliglot.js (for multilang).

因此可以在我的Lang类中使用new Polyglot(...):

So to be able use new Polyglot(...) in my Lang class:

export class Lang
{
    ...
    constructor() {

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

我使用这四种方法

A.在我相当老的(2016年)angular2中(基于framerwork angular2 -webpack-starter )项目(当前,由于在新的角度项目中缺少require指令,因此该解决方案无法正常工作):

A. In my quite old (2016) angular2 (based on framerwork angular2-webpack-starter) project (currently this solution doesn't work due to lack of require instruction in new angular projects):

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

B.在我的下一个项目angular4(基于 angular2-webpack-starter ):

B. In my next project angular4 (based on angular2-webpack-starter):

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

C.在我最近嵌入Laravel项目的angular5项目中(基于 angular -cli )

C. In my recent angular5 project embeded in Laravel project (based on angular-cli)

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

D..我还发现了第4个解决方案,该解决方案适用于我的一些旧的jQuery项目(基于 angular2-webpack-starter )(互联网上的人们经常提到此解决方案),但我使用Polyglot示例将其写下来:

D. I also found 4-th solution which work on my some old angular project for jQuery (based on angular2-webpack-starter) (and people in internet mention this solution a lot) but I write it down using Polyglot example:

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

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

问题是:这四个解决方案之间有什么区别以及它们如何工作?是什么原因导致某些项目中的一种解决方案有效,而其他解决方案无效?

推荐答案

所以让我们分解一下:

A:仍然可以在您只需要在使用前声明require的任何角度版本中使用.

A: Would still work in any angular version you just have to declare require before using it.

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

B:点A使用CommonJS模块系统加载依赖项,其他点使用ES6动态导入系统(可以与 webpack .如果该库公开了模块,例如,您可以直接导入Polyglot.

B: Point A uses the CommonJS module system to load the dependency, the other points are using the ES6 dynamic import system (which can be used like the commonjs module system with webpack by default). You can import Polyglot directly if the library exposes the module e.g.

export class Polyglot {}

C:如果Polyglot有多个您都不希望使用的成员,则可以通过编写来导入Polyglot的所有成员

C: If Polyglot has multiple members which you all wan't to use you can import all members of Polyglot by writing

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

D:导入了Polyglot,但未绑定到任何变量.但是,Polyglot会公开一个全局对象,除非您声明该变量将在以下对象下可用,否则您将无权访问该对象.

D: Polyglot gets imported but not bind to any variable. But Polyglot exposes a global object which you don't have any access to until you declare the variable it will be available under.

请参见 mdn参考更好的解释

取决于您使用的构建系统,没有答案哪个应该一直有效,但是我的解决方案A应该在每个Webpack构建以及B和C中都可以使用.友好提醒您,A和D并不是最佳解决方案,应该仅如果没有其他方法可以导入/使用该模块,则可以使用.

Depending on what build system you use there is no answer which one of the should always work but my solution A should work in every webpack build aswell as B and C. Friendly reminder that A and D are no optimal solutions and should only be used if there is no other way to import/use the module.

ES6标准仅描述了什么是模块,包含什么模块,应该如何导出模块已导入等.

The ES6 standard just describes what a modules is, what it contains, how a module should be exported and imported and more on.

因为ES6不是库或类似的东西,所以没有办法处理ES6的这些旧"模块. CommonJS 也是一个标准,由Node.js实现,该模块导入您使用require('module')知道的模块

So there is no way how ES6 would handle these "old" modules since it isn't a library or anything like that. CommonJS is also just a standard, which is implemented by Node.js which module imports you know with require('module').

因此,Webpack可以帮助您处理这两个模块系统,因为它们同时实现了这两个模块.

So Webpack comes into your help which can handle both of these module systems, because they implemented both of these.

如果您创建一个空项目并通过webpack --env development使用webpack进行构建,则可以看到webpack如何处理不同的模块. Webpack会为ESModules或CommonJS Modules编译代码和广告,并由其自己处理.根据找到的模块,它们将调用不同的方法.我在编译后的代码中添加了一个示例.

If you create an empty project and build with webpack via webpack --env development, you can see how webpack handles the different modules. Webpack compiles your code and ads it's own handling for ESModules or CommonJS Modules. Depending on what module they find they will call different Methods. I added an example with the compiled code.

/******/ (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,模块-> CommonJS)中,您可以看到Webpack处理不同的类型.如果您想要更深入的了解,我可以再次编辑我的帖子.

You can see that Webpack creates a self executing function which gets all the created modules with their { id(pathToFile) : function(module, exports, __webpack_require__). In the 2 different module types (ESModule, Module --> CommonJS) you can see that Webpack handles the types differently. If you want a more in depth look i can edit my post again.

这篇关于导入第三方js文件到angular typescript项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:10