How to access node.js module in RequireJS (AMD) environment?

I have a front-end SPA using RequireJS (2.1.14) as a modular system. It mainly downloads and downloads the 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 problem is that I would like to download some npm packages (e.g. npm install config) from the RequireJS module. RequireJS cannot find the npm node_modules , which is in a different directory than the RequireJS baseUrl directory .

The following is my directory structure:

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

The following is the error message:

script error

He tried to load the module from the baseUrl directory.

How can I access the npm module from the RequireJS module system in my use case?

+5
source share
1 answer

It is not possible to use RequireJS on a client (browser) to access files from node_modules. . Files under node_modules must first be copied to an accessible location (in the public section) before the client can access them. The documentation says that RequireJS can access Node modules , but this only works for server-side JavaScript (if you want to use the RequireJS-style module syntax in Node).

To use your config module in a client application, you must first convert it to a RequireJS compatible module and copy it to public . . This article explains how to automate this with package managers and build tools , and contains a quote that finally fixed my broken understanding of RequireJS + Node:

To use Node modules in a browser you will need a build tool. This may bother you. If this is a deal breaker, then everything means that you continue to spend your life copying and pasting code and arranging script tags.

+6
source

Source: https://habr.com/ru/post/1232399/


All Articles