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

柔情痞子 提交于 2019-12-19 02:57:16

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32808991/how-to-access-node-js-module-in-requirejs-amd-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!