Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import RequireJS (AMD) module in Angular 4.x (Angular Cli) App?

I have a legacy JS file, written in the following RequireJS (AMD) module notation:

define('mymodule', [], function(){

    // ... bla bla bla

    return {
        calculate: function() { return 1 + 1; }
    };
});

I'm importing this file from another (legacy) project that uses RequireJS, therefore - I can't change the module definition used.

I want to import it in an Angular Cli (Angular 4.x) app written in TypeScript.

Since Angular Cli uses Webpack 2 to build projects, which supports AMD, I thought I can import it like this:

import * as MyModule from './mymodule.js';

... but that's not working, it triggers an error that the mymodule.js is not a module.

Any ideas (or workarounds) how can I import this legacy module?

like image 447
Kaloyan Kosev Avatar asked May 22 '17 14:05

Kaloyan Kosev


1 Answers

I am able to load amd module.

here is TS:

import * as MyModule from './mymodule.js';

console.log('my value is', MyModule.value);

mymodule.js file:

define(["require", "exports"], function(require, exports){
   exports.value = "aaa";
});

and in tsconfig.js

"allowJs": true

UPDATE:

You can use System.import provided by webpack.

 declare var System: any; 

 System.import('./mymodule.js')
     .then(MyModule=>console.log(MyModule.value));
like image 131
Julia Passynkova Avatar answered Sep 20 '22 22:09

Julia Passynkova