NodeJS local modules for complex application structures

前端 未结 3 1731
刺人心
刺人心 2021-01-06 12:05

I\'m currently part of team building a Windows 8 application using JavaScript. We are using npm and browserify to manage dependencies and convert our modules to AMD browser

3条回答
  •  梦谈多话
    2021-01-06 12:19

    The problem of the require() function is that the paths are relative from the current file. You could put your modules inside the node_modules directory but this is the worst thing you could do. node_modules is the directory where live all the third-party modules. If you follow this simple rule it's very easy and handy to stay always up to date, you can remove all the dependencies (removing the node_modules) and just doing npm install.

    The best solution is to define your own require function and make it global. For example:

    Your project structure is:

    my-project
    | tools
    |- docs
    |- logs
    |- conf
    `- src
       |- node_modules
       |- package.json
       |- mod.js
       |- a
       |  `- b
       |     `- c.js
       `- d
          `- app.js
    

    mod.js

    global.mod = function (file){
      return require ("./" + file);
    };
    

    app.js

    //This should be the first line in your main script
    require ("../mod");
    
    //Now all the modules are relative from the `src` directory
    //You want to use the a/b/c.js module
    var c = mod ("a/b/c");
    

    That's all, easy. If you want to get a third-party module located in node_modules use require(). If you want to get your own modules use mod().

    And remember, node_modules is only for third-party modules, rule nº1.

提交回复
热议问题