Search code examples
javascriptangulartypescriptcodemirror

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


I'm playing with ot.js and CodeMirror editor with Angular 4. Unfortunately, I have issue importing some components of ot.js into Angular 4 component.

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

It looks like some components of ot.js require global variable to be defined before importing. See the code below:

/* 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);

  ...
}

When codemirror-adapter is imported I get the following error:

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)

How do I make sure that ot variable is available for codemirror-adapter ?

Update1:

I tried the following which didn't help:

declare const ot: any

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

and

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

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

Update2: Adding scripts to 'scripts' section of .angular-cli.json file.

The trick was to add the file which declares ot variable.

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

Thanks!


Solution

  • The trick was to add files that define ot variable to 'scripts' section of .angular-cli.json

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

    Thanks @Jong-Hyun Kim for bringing me back to this track.