7

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?

1 Answer 1

13
+50

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));
Sign up to request clarification or add additional context in comments.

6 Comments

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)?
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));
Unfortunately, this doesn't work either. TypeScript error: Cannot find name 'System'
add "declare var System: any;"
Lol, great! That solved it!! Please update your answer, so I can accept it and reward you with the bounty :-) Thank you!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.