如何在RequireJS(AMD)环境中访问node.js模块? [英] How to access node.js module in RequireJS (AMD) environment?
问题描述
我有一个使用 RequireJS
(2.1.14)作为模块系统的前端SPA。它基本上是bootstrap并加载 Backbone.Marionette
app。
I have a front-end SPA using RequireJS
(2.1.14) as module system. It basically bootstrap and load Backbone.Marionette
app.
在 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
来自 RequireJS
模块的包(例如npm install config)。 RequireJS
似乎无法找到位于<$ c $以外的目录的npm node_modules
目录c> RequireJS baseUrl 目录。
The issue is, I would like load some npm
packages (e.g npm install config) from RequireJS
module. RequireJS
can't seem to find npm node_modules
directory which is sitting at different directory than RequireJS baseUrl
directory.
以下是我的目录结构:
my_project/
app/
public/
js/
main.js
app.js
node_modules/
config/
以下是错误消息:
它试图从baseUrl目录加载模块。
It tried to load module from baseUrl directory.
如何从RequireJS模块系统访问npm模块我的用例?
How can I access npm module to from RequireJS module system in my use case?
推荐答案
无法在客户端(浏览器)上使用RequireJS来访问 node_modules。
首先必须将 node_modules
下的文件复制到可访问的位置(在<$ c下) $ c> public 文件夹)在客户端可以访问它们之前。文档说明 RequireJS可以访问节点模块,但这仅适用于服务器 - side JavaScript(当您想在Node中使用RequireJS样式的模块语法时)。
It is not possible to use RequireJS on the client (browser) to access files from node_modules.
Files under node_modules
must first be copied to a location that is accessible (under the public
folder) before the client can access them. The documentation says RequireJS can access Node modules, but this only works for server-side JavaScript (when you want to use RequireJS-style module syntax in Node).
使用 config <客户端应用程序中的/ code>模块,您必须先将其转换为与RequireJS兼容的模块并将其复制到
本文解释了如何使用包管理器和构建工具自动执行此操作 ,并包含最终修复了我对RequireJS + Node的理解的引用: public
下。
To use your config
module in the client app, you must first transform it into a RequireJS-compatible module and copy it under public
. This article explains how to automate this with package managers and build tools, and contains the quote that finally fixed my broken understanding of 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.
这篇关于如何在RequireJS(AMD)环境中访问node.js模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!