AngularJS convention for multiple files [closed]

▼魔方 西西 提交于 2020-01-03 13:04:22

问题


I was wondering if there are best practices for avoiding monolithic js files in AngularJS.

I would like to avoid having very large controllers.js/filters.js/services.js files. Instead, for the sake of manageability, I would like to have each controller/filter/service in its own file.

I would like to know, if there is a recommended convention for this approach as far as the directory structure and naming convention is concerned.

Also, what might be the best way to avoid adding a script tag in my app/index.html for each new file I create?


回答1:


You may check this app: https://github.com/angular-app/angular-app

It is good example to start with.

Also, what might be the best way to avoid adding a script tag in my app/index.html for each new file I create?

It can be automated by grunt watcher for example. I use such a config for this task:

grunt.initConfig({
    index: {
        files: ['app/js/**/*.js'],
        tasks: 'index:scripts'
    }
})

grunt.registerMultiTask('index', 'Create index.html',
        function() {        
            var files = grunt._watch_changed_files || grunt.file.expand(this.data);
            var now = new Date().getTime();
            var scripts_str = '';
            var tpl = grunt.file.read('app/index.html.tmpl');


            files.forEach(function(file) {
                file = file.replace(/^app\//, '');
                scripts_str += '<script src="' + file + '?bust=' + now + '"></script>' + "\n";
            });   

            grunt.file.write('app/index.html', grunt.template.process(tpl, {
                data: {
                    scripts: scripts_str
                }
            }))
            console.log('File "index.html" created.');

        });

index.html.tmpl:

<html>
<body>
    ...
    <%=scripts%>
</body>
</html>



回答2:


There are a few conventions out there and it doesn't really appear that any "best practice" has emerged yet.

That being said, the two conventions that I like put each controller/filter/service/etc in their own directory. As far as directory structure, for smaller projects I've seen a directory for each type of file. For large projects, I've seen a directory for each module with all controllers/filters/services for that module in that folder. This also forces you to split your app up into modules which is a nice side effect.



来源:https://stackoverflow.com/questions/18241143/angularjs-convention-for-multiple-files

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