I have a front-end SPA using RequireJS
(2.1.14) as module system. It basically bootstrap and load Backbone.Marionette
app.
In 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!');}
});
});
});
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.
Below is my directory structure:
my_project/
app/
public/
js/
main.js
app.js
node_modules/
config/
Below is error message:
It tried to load module from baseUrl directory.
How can I access npm module to from RequireJS module system in my use case?
Yes! The Node adapter for RequireJS, called r. js, will use Node's implementation of require and Node's search paths if the module is not found with the configuration used by RequireJS, so you can continue to use your existing Node-based modules without having to do changes to them.
Generally, these external modules are published in Node Package Manager (NPM) registry, so to use external modules in our application first, we need to install the external module codebase from NPM locally using Npm install module_name command.
Module.exports API to expose Data to other files Node supports built-in module system. Node. js can import functionality which are exposed by other Node. js files.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With