【发布时间】:2016-07-15 16:43:59
【问题描述】:
我在正确安装来自 cdn url 的 js 时遇到问题,在浏览了 10 多篇文章或帖子后,我找不到一个好方法。
我要安装以在我的 Angular 项目中使用的 js 文件是 http://player.twitch.tv/js/embed/v1.js。目前,我的 index.html 中只有一个脚本标签来加载它。
在一个组件文件中,我有 this.player = new Twitch.Player("video-player", options); 之类的代码,但是当我运行 npm start 时,我得到一个错误错误 TS2304: Cannot find name 'Twitch'。
奇怪的是,如果我注释掉使用“Twitch”的行,我可以启动我的服务器,然后我在服务器运行时取消注释掉这些行,然后应用程序可以正常工作,利用 Twitch 播放器库没有任何问题。
我相信我需要将它安装在 system.config.js 文件中,但我找不到如何为来自 cdn 的 js 执行此操作(这不能通过 npm 获得)。我已经为多个 npm 包做了这个,但是从 cdn 我有点迷路了。
我不能 100% 确定我是否需要在 systemjs 中执行此操作,所以如果这不正确,请忽略本文的其余部分并让我知道您的建议 - 我只需要 js 文件中的 Twitch在我的应用程序中被识别和使用。
我找到了几种不同的方法来尝试这个。一个是load the module directly from the url。
// index.html
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
System.import('http://player.twitch.tv/js/embed/v1.js');
</script>
// main.js
import {bootstrap} from '@angular/platform-browser-dynamic';
import {AppComponent} from './app.component';
import "angular2-materialize";
import "twitch-api";
使用这种方法,我不确定如何将其加载到我的应用程序中。 import "twitch-api" 不像使用 npm 包(如 angular2-materialize)那样工作,因为它没有映射到 system.config.js 文件中。不确定这种方式是否可行。
另一种方式是load it in the system.config.js file。使用这种方法,我将带有 url 的地图对象添加到 js 文件中。我想可能整个 system.config.js 文件都是相关的,所以我将其全部粘贴在下面。
在 main.ts 中,我执行与上面添加 import "twitch-api"; 相同的操作。完成这些更改后,我在尝试启动服务器 TS2304: Cannot find name 'Twitch' 时仍然收到相同的错误消息。
var map = {
'app': 'app', // 'dist',
'rxjs': 'node_modules/rxjs',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'@angular': 'node_modules/@angular',
"materialize-css": "node-modules/materialize-css",
"materialize": "node_modules/angular2-materialize",
"angular2-materialize": "node_modules/angular2-materialize",
"angular2-localstorage": "node_modules/angular2-localstorage",
"twitch-api": "http://player.twitch.tv/js/embed/v1.js"
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
"materialize-css": { main: "dist/js/materialize" },
"materialize": { main: "dist/materialize-directive", defaultExtension: "js" },
"angular2-localstorage": {main: "index.js", defaultExtension: 'js'},
"twitch-api": {}
};
var packageNames = [
'@angular/common',
'@angular/compiler',
'@angular/core',
'@angular/http',
'@angular/platform-browser',
'@angular/platform-browser-dynamic',
'@angular/router',
'@angular/router-deprecated',
'@angular/testing',
'@angular/upgrade',
''
];
// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
var config = {
map: map,
packages: packages
}
System.config(config);
【问题讨论】: