2016-11-21 53 views
0

有人可以告诉我如何使用SystemJS加载一个简单的JavaScript文件到浏览器。systemjs - 加载jQuery的

我想从我的node_modules jQuery中加载文件夹使用以下syntax-:

packages: { 
     app: { 
     main: './js/main.js', 
     defaultExtension: 'js' 
     }, 
     rxjs: { 
     defaultExtension: 'js' 
     }, 
     'jquery': { 
     main: 'node_modules/jquery/dist/jquery.min.js' 
    } 
    } 

但每当我写了下面的线在我的浏览

$(document).ready(function(){alert("Hello");}); 

我的整个SystemJS配置 - :

/** 
* System configuration for Angular samples 
* Adjust as necessary for your application needs. 
*/ 
(function (global) { 
    System.config({ 
    paths: { 
     // paths serve as alias 
     'npm:': 'node_modules/' 
    }, 
    // map tells the System loader where to look for things 
    map: { 
     // our app is within the app folder 
     app: 'app', 
     // angular bundles 
     '@angular/core': 'npm:@angular/core/bundles/core.umd.js', 
     '@angular/common': 'npm:@angular/common/bundles/common.umd.js', 
     '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', 
     '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', 
     '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', 
     '@angular/http': 'npm:@angular/http/bundles/http.umd.js', 
     '@angular/router': 'npm:@angular/router/bundles/router.umd.js', 
     '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', 
     '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js', 
     // other libraries 
     'jquery':     'npm:jquery/dist/jquery.min.js',  
     'rxjs':      'npm:rxjs', 
     'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js' 
    }, 
    // packages tells the System loader how to load when no filename and/or no extension 
    packages: { 
     app: { 
     main: './js/main.js', 
     defaultExtension: 'js' 
     }, 
     rxjs: { 
     defaultExtension: 'js' 
     } 
    } 
    }); 
})(this); 

我得到一个错误,未定义$。

如何使用SystemJS将简单的.js文件加载到浏览器中?

+0

您是否尝试使用'jQuery'代替'$'? – jkris

+0

@jkris烨同样的效果。 jQuery没有定义。 –

回答

1

此行为是正确的和预期的,因为作为一个写得很好的环境友好的库,如果合适的加载程序可用,jQuery不会无条件地将自身注入到浏览器中的全局名称空间window中。 SystemJS检测到jQuery是一个AMD模块,并提供正确的包装,使其使用AMD define api正确注册。

这意味着您需要导入它才能使用它。如果你想获得它在你的浏览器控制台

下面的代码将打字稿和巴贝尔

import $ from 'juery'; 

$(document).ready(() => { 
    alert("Hello"); 
}); 

下工作。您可以执行以下操作:

// In your browser tools console 
SystemJS.import('jquery').then(({default}) => { 
    window.$ = default; 
});