我有一个使用RequireJS(2.1.14)作为模块系统的前端SPA.它基本上是bootstrap并加载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下的文件复制到可访问的位置(在公用文件夹下),然后客户端才能访问它们.文档说
RequireJS can access Node modules,但这仅适用于服务器端JavaScript(当您想在Node中使用RequireJS样式的模块语法时).
要在客户端应用程序中使用配置模块,必须先将其转换为与RequireJS兼容的模块,然后将其复制到公共模块下.这篇文章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.