如何在Angular 4.x(Angular Cli)App中导入RequireJS(AMD)模块? [英] How to import RequireJS (AMD) module in Angular 4.x (Angular Cli) App?

查看:170
本文介绍了如何在Angular 4.x(Angular Cli)App中导入RequireJS(AMD)模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧版JS文件,它使用以下RequireJS(AMD)模块表示法编写:

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; }
    };
});

我正在从另一个使用RequireJS的(旧版)项目中导入此文件,因此-我无法更改所使用的模块定义.

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

我想将其导入用TypeScript编写的Angular Cli(Angular 4.x)应用程序中.

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

由于Angular Cli使用Webpack 2来构建支持AMD的项目,所以我认为我可以这样导入它:

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';

...但是不起作用,它会触发错误消息,指出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?

推荐答案

我能够加载amd模块.

I am able to load amd module.

这是TS:

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

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

mymodule.js文件:

mymodule.js file:

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

以及在tsconfig.js中

and in tsconfig.js

"allowJs": true

更新:

您可以使用webpack提供的System.import.

You can use System.import provided by webpack.

 declare var System: any; 

 System.import('./mymodule.js')
     .then(MyModule=>console.log(MyModule.value));

这篇关于如何在Angular 4.x(Angular Cli)App中导入RequireJS(AMD)模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆