javascript - 如何在 RequireJS (AMD) 环境中访问 node.js 模块?

标签 javascript node.js requirejs

我有一个使用 RequireJS (2.1.14) 作为模块系统的前端 SPA。它基本上引导并加载 Backbone.Marionette 应用程序。

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

});

});

问题是,我想从 RequireJS 模块加载一些 npm 包(例如 npm install config)。 RequireJS 似乎无法找到与 RequireJS baseUrl 目录 位于不同目录的 npm node_modules 目录。

下面是我的目录结构:

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

错误信息如下:

script error

它试图从 baseUrl 目录加载模块。

在我的用例中,如何从 RequireJS 模块系统访问 npm 模块?

最佳答案

无法在客户端(浏览器)上使用 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 + Node 的错误理解的引用:

In order to use node modules on the browser you will need a build tool. This might bother you. If this is a deal breaker then by all means continue wasting your life copying and pasting code and arranging your script tags.

关于javascript - 如何在 RequireJS (AMD) 环境中访问 node.js 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32808991/

相关文章:

javascript - 使用 jQuery 同时向下滑动 div 和 .fadeIn() 内容,反之亦然?

java - 如何在 VerticalPanel 的 onPreviewDrop() 中获取 Widget 的索引?

javascript - 单击时删除特定按钮(从 DOM)

javascript - 如何获取正在加载html页面的页面路径?

javascript - 使用 Javascript Regex 转义 Lucene 字符

jquery - 将 Jquery.hammer 和 Hammer 2.0.2 与 RequireJS 结合使用

python - 使用 Nodejs 中的前端和 Python 中的后端服务器运行 Google App Engine 的一个实例

node.js - 在centos 6.4和nginx上将cakephp 2.4与redis连接

javascript - requirejs 模块未定义

javascript - 将 moment.js 与 lang 文件和 require.js 一起使用