如何在 Angular 4.x (Angular Cli) App 中导入 RequireJS (AMD) 模块? [英] How to import RequireJS (AMD) module in Angular 4.x (Angular Cli) App?
问题描述
我有一个旧的 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屋!