문제

I'm currently working on a big JavaScript project for which we want to define our own API. I'm using RequireJS as my dependency loader and it suits me just fine, allowing me to define modules in their respective file. I do not make use of my own namespace, a module returns an instance, which can be used in other modules, i.e.:

define(
    ['imported_module'],
    function(module){
        module.doSomething();
    }
)

However as the number of files grows, I'd like to decide how to structure these files in folders. Currently I use the following scheme to name my files:

[projectname].[packagename].[ModuleName]

An example could be stackoverflow.util.HashMap.js. I would like to introduce a project folder, a folder per package and rename the files to the module name, like:

stackoverflow/util/HashMap.js

This structures my code quite neatly into folders, however the filename reflects only the module now. I'd like to define some kind of routing to be able to define how RequireJS should look for files. Example:

The file

stackoverflow/util/stackoverflow.util.HashMap.js

Should be importable by the statement

define(['stackoverflow.util.HashMap'],function(HashMap){});

Has anyone experience with structuring large JavaScript projects and if so, could you share your approach?

도움이 되었습니까?

해결책

You shouldn't specify the routing info on your js file names, those are the namespace and folder paths' jobs. So stackoverflow/util/HashMap.js is just fine. And you can use define("stackoverflow/util/HashMap", ....) to tell the dependency.

If you need to put your modules in a different folders, you can config paths for your loader, see this manual from RequireJS API.

There's no best way for structure your js files. But put the root namespace in a src folder is always a good practice. You can see the dojo source code and YUI source code and use similar ways for your project. They both are large scale Javascript projects.

다른 팁

actually it's better to get js lib routing to load all js using standard interface: "js.yoursite.com/lib-0.2.js" there should be a router (php or other, and able to cache queries). So there you could determine and control whole pathes that you use. Because common jquery plugin should stay at one dir, with jquery, and your own custom plugins not.

And there you control each project by it's own rules:

jquery/
  plugins/
    jquery.prettyPhoto.js
  jquery.min.js

mySuperJS/
  stable.0/ -- there your production version for 1.0 branch
    module.js
  0.1/
    module.js
  0.2/
    module.js
  0.3/
    module.js

myOtherlib/
  stable.0/ -- production version for all 0.* versions
  stable.1/ -- production version for all 1.0 versions
  0.1/
  0.2/
  0.3/
  0.4/
  0.4.1/
  0.4.1.18/

We're using such structure around a year and it's the best for us. But sometimes we use more complex solution and separate all modules for libs, plugins, tools, components and apps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top