我有一个使用 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/
错误信息如下:
它试图从 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/