6

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?

Kaloyan Kosev
  • 12,483
  • 8
  • 59
  • 90

1 Answers1

13

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));
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32
  • It indeed works when the `mymodule.js` file has this `exports` injected and when the public module methods (values) are defined this way: `exports.value = "aaa";` However, my use-case is different. My `mymodule.js` file has different logic. The `define` statement lacks injection of the `exports` and it simply returns the public module methods (or values). Do you have any suggestions if I can import it **without** changing logic/structure in my `mymodule.js` (sadly, that's a primary requirements I need to deal with)? – Kaloyan Kosev May 29 '17 at 11:32
  • This is named modules and i have no idea why they do not work. Try to do System.import('./mymodule.js').then(x=>console.log(x)); – Julia Passynkova May 29 '17 at 14:30
  • 1
    Unfortunately, this doesn't work either. TypeScript error: `Cannot find name 'System'` – Kaloyan Kosev May 29 '17 at 14:36
  • 2
    add "declare var System: any;" – Julia Passynkova May 29 '17 at 14:37
  • Lol, great! That solved it!! Please update your answer, so I can accept it and reward you with the bounty :-) Thank you! – Kaloyan Kosev May 29 '17 at 14:52
  • Is there any guide anywhere to use Angular 5 with requireJS? I'm trying to insert an Angular5 app into an AngularJS ngView (route of route) – Sampgun Jan 18 '18 at 08:09