关于javascript:在Angular中进行其他导入之前,如何从第3部分脚本中导入全局变量?

How to import global variable from 3rd-part script before other import in Angular?

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* 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时,出现以下错误:

1
2
3
4
5
6
7
8
9
10
11
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:

我尝试了以下无济于事的方法:

1
2
3
4
declare const ot: any

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

1
2
3
4
5
declare var require: any;
const ot = require('ot');

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

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

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

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

谢谢!


技巧是将定义ot变量的文件添加到.angular-cli.json的"脚本"部分

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

感谢@ Jong-Hyun Kim让我回到了这首单曲。


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


您是否尝试过这种方式?

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

然后导入其他东西

1
import ....