javascript - 如何将使用旧导入方法的第 3 方库包含到 Angular4.x 中?

标签 javascript angular typescript jhipster

include the library 的正确工作流程是什么?到 Angular 4.0 并在组件中使用它?

我的步骤:

yarn add mathjs

那么应该有一种方法可以在其中一个构建生命周期中注入(inject) js 库,以便 angular4 组件可以使用它。 JHipster 利用 Webpack 和 Yarn。

然后我尝试添加到组件(docs):

import { mathjs } from "./mathjs";  

var math = require('mathjs');

那些没有用。我错过了什么?

更新:

似乎 mathjs 使用旧方法建议 var math = require('mathjs')。也许类似于JQuery question在某种程度上...

UPDATE2

最佳答案

这是一个很好的问题,我很高兴你提出这个问题,因为我希望我在第一次遇到这个小问题时就知道我将要写的东西。在成为 Angular 问题之前,这是一个 typescript /javascript 和 webpack 问题。我绝对计划在 my blog 上写一篇文章尽快。

您的场景:

你跑

npm install mathjs
  1. 现在您尝试在组件中使用 math.js:
  2. 找到 math.js dist js 文件 (node_modules/mathjs/dist/math.js) 并像这样引用

    从“../../node_modules/mathjs/dist/math”导入{mathjs};

  3. 但是您收到错误消息说“set --allowJS”。您可以这样做:

    在配置中设置 --allowJS (tsconfig.json) { “编译器选项”:{ "allowJs": true, ...

  4. 现在你得到:

ERROR in ../node_modules/mathjs/dist/math.js (12209,13): Unreachable code detected.

  1. 查看 math.js 源代码,您会发现它是一个老式模块,但没有根包装器函数(一个函数将它们全部引入并在黑暗中绑定(bind)它们..)(稍后会详细介绍)。

解决方案:为目标库 (@types/mathjs) 安装一个类型文件

  1. 首先,检查您是否可以在此处为您的模块获取@typings 文件 https://microsoft.github.io/TypeSearch/
  2. 从 npm (https://www.npmjs.com/package/@types/mathjs) 获取 mathjs 类型文件并运行 npm install 以将类型 .d.ts 文件添加到目标库的 node_modules 目录

    npm install --save @types/mathjs

  3. 正确添加类型引用

    从“mathjs”导入 * 作为 mjs

像这样使用它:

console.log("e was: " + mjs.e);

我的 github 上有 math.js 库的完整解决方案 https://github.com/res63661/importOldJSDemoWithTypings/

更多: 例如,只看你自己的 Angular 项目。在使用 ng new 创建新项目后,每次运行 npm install 时,CLI 都会创建 node_modules 文件夹。深入了解这里并注意许多 .js 文件的 d.ts 文件。

当打乱打字或定义您自己的(.d.ts 文件)时,请务必在构建之间重新启动服务器,因为打字目前似乎不会即时更新

进一步阅读:

  1. http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html
  2. https://angular.io/guide/typescript-configuration#typescript-typings
  3. https://microsoft.github.io/TypeSearch/

最后:

如果您处于紧要关头并且这对您不起作用,我确实通过将它包装在主导出类型中成功地为不同的(小得多的)模块创建了自定义包装器

export var moduleNamer = (function(){
  //module implementation
}());

然后将 .js 文件转储到我的组件本地,然后按如下方式引用它:

//reference like this from your component:
import {moduleNamer} from "./source";  //from source.js

--丰富

关于javascript - 如何将使用旧导入方法的第 3 方库包含到 Angular4.x 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45549698/

相关文章:

javascript - 如何在 HTML 的下拉列表中设置条件?

javascript - 如何从 addEventListener 中删除重复项

Angular BehaviorSubject 订阅只触发一次

typescript - 将js文件加载到 typescript 文件中

javascript - 由于表单未连接而取消表单提交

javascript - 为什么<a id ="test"/>会脱离DOM链?

visual-studio - Angular 2 代码片段扩展(来自 Mads)在 VS 2017 中不起作用

angular - 如何在 Angular Universal 中向 <body> 添加类?

Angular 4 - 在下拉列表中找到选定的值

angular - 如何在 Angular2 中使用 Luxon?