javascript - 如何在 Angular 中进行其他导入之前从第三部分脚本导入全局变量?

标签 javascript angular typescript codemirror

我正在使用 Angular 4 来使用 ot.js 和 CodeMirror 编辑器。不幸的是,我在将 ot.js 的一些组件导入 Angular 4 组件时遇到问题。

ot.js 源 - https://github.com/Operational-Transformation/ot.js/tree/master/lib

看起来 ot.js 的某些组件需要在导入之前定义全局变量。请参阅下面的代码:

/* Next line imports the following js files from ot.js:
 ../ot/lib/editor-socketio-server.js
 ../ot/lib/index.js
 ../ot/lib/selection.js
 ../ot/lib/text-operation.js
 ../ot/lib/server.js
 ../ot/lib/simple-text-operation.js
 ../ot/lib/wrapped-operation.js
 ../ot/lib/client.js
*/
import * as ot from 'ot'
// This seems to require 'ot' global variable to be defined before importing this file. Looks like 'CodeMirrorAdapter' is attached to 'ot'            
import 'ot/lib/codemirror-adapter'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  @ViewChild('editor') editor;

  // This works fine if no 'codemirror-adapter' imported: ot variable is defined
  otClient = new ot.Client(0);

  // This fails with error below: ot is not defined
  cma = new ot.CodeMirrorAdapter(this.editor.instance);

  ...
}

导入 codemirror-adapter 时,出现以下错误:

Uncaught ReferenceError: ot is not defined
    at Object.../../../../ot/lib/codemirror-adapter.js (codemirror-adapter.js:3)
    at __webpack_require__ (bootstrap 010ad1c…:54)
    at Object.../../../../../src/app/app.component.ts (main.bundle.js:52)
    at __webpack_require__ (bootstrap 010ad1c…:54)
    at Object.../../../../../src/app/app.module.ts (app.component.ts:14)
    at __webpack_require__ (bootstrap 010ad1c…:54)
    at Object.../../../../../src/main.ts (environment.ts:8)
    at __webpack_require__ (bootstrap 010ad1c…:54)
    at Object.2 (main.ts:11)
    at __webpack_require__ (bootstrap 010ad1c…:54)

如何确保 ot 变量可用于 codemirror-adapter

更新1:

我尝试了以下方法,但没有帮助:

declare const ot: any

import * as ot from 'ot'
import 'ot/lib/codemirror-adapter'

declare var require: any; 
const ot = require('ot'); 

import * as ot from 'ot'
import 'ot/lib/codemirror-adapter'

更新2: 将脚本添加到 .angular-cli.json 文件的“scripts”部分。

诀窍是添加声明ot变量的文件

"scripts": [
  "../node_modules/ot/lib/client.js",
  "../node_modules/ot/lib/text-operation.js"
],

谢谢!

最佳答案

我解决了同样的问题。 声明 const ot: any

关于javascript - 如何在 Angular 中进行其他导入之前从第三部分脚本导入全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45292324/

相关文章:

angular - Validators.minlength 不适用于 Angular react 形式

javascript - TypeORM - 3 个相关表之间的 LEFT JOIN/INNER JOIN 问题

jquery - 如何获得正确的表格格式? Jquery问题

javascript - PWA 路由和深度链接 SPA 或无 SPA、框架或无框架

node.js - 我如何在 wamp 中运行 Angular 6 应用程序?

Angular 2 : have component auto detect variable change in a service

javascript - 混合类型 react 的映射函数中的 typescript 类型问题

javascript - 在其他元素之上显示隐藏元素

javascript - 为色度计生成#CCCCCC 和#3B5998 之间的颜色?

javascript - JQuery/Javascript 翻页