2015-09-27 50 views
5

我有一個使用RequireJS(2.1.14)作爲模塊系統的前端SPA。它基本上引導並加載Backbone.Marionette應用程序。如何訪問RequireJS(AMD)環境中的node.js模塊?

main.js

require.config ({ 
    baseUrl: '/js', 
    waitSeconds: 200, 
    nodeRequire: require, 
    paths: { 
    jquery: '//cdn/jquery.min',   
    underscore:'//cdn/underscore-min', 
    // more plugins 
    }, 
    shim: { 
     // shimming stuff 
    } 
}); 

require(['marionette', 
    'vent', 
    'config/template', 
    'app', 
    'routers/main' 
    ], 
function (Marionette, 
     vent, 
     Template, 
     nrtApp 
) { 
'use strict'; 

nrtApp.module ('Public.Main', function (Main, nrtApp, Backbone,Marionette, $, _) { 
    nrtApp.start(); 

    // this is where the error is: 
    requirejs (['config'], function (config) { 
    if (typeof config !== 'undefined') {config.log ('ok!');} 
    }); 

}); 

}); 

的問題是,我想加載一些npm包(例如NPM安裝配置)從RequireJS模塊。 RequireJS似乎無法找到位於與RequireJS baseUrl目錄不同目錄的npm node_modules目錄。

下面是我的目錄結構:

my_project/ 
    app/ 
     public/ 
      js/ 
       main.js 
       app.js 
    node_modules/ 
     config/ 

下面是錯誤消息:

script error

它試圖從目錄中的baseUrl加載模塊。

如何在我的用例中從RequireJS模塊系統訪問npm模塊?

+0

從客戶端只能訪問公用文件夾。 node_modules中的配置是什麼?如果該模塊也在客戶端上工作,那麼您必須將其複製到public/js中才能使用它。 – Molda

+0

@Molda config是一個npm模塊。是的,我想在客戶端應用程序中使用配置。 –

回答

6

這是不可能使用客戶端(瀏覽器)上RequireJS從node_modules.文件訪問文件node_modules下必須首先被複制到可訪問(在public文件夾下)之前在客戶端可以訪問它們的位置。該文檔說RequireJS can access Node modules,但這隻適用於服務器端 JavaScript(當您要在Node中使用RequireJS風格的模塊語法時)。

要在客戶端應用程序中使用config模塊,必須先將其轉換爲RequireJS兼容模塊並將其複製到public下。本文explains how to automate this with package managers and build tools,幷包含最終確定我RequireJS +節點的破認識報價:

爲了使用上的瀏覽器節點模塊,您將需要一個構建 工具。這可能會打擾你。如果這是一個交易斷路器,那麼所有的 意味着繼續浪費你的生活複製和粘貼代碼和 排列你的腳本標籤。

相關問題