Best Practice for Including Javascript and Concatenate

时间:2015-05-04 19:50:05

标签: javascript module include concatenation gulp

I have a medium sized project and I want to divide my fairly long javascript file into several submodules. Afterwards I want to concatenate all my js files with gulp.js and also minify them.

I also would prefer not to use a watch task to concatenating my js every time I edit it, but rather use the separated js modules during development and for deployment I'd like to run my gulp concat task. (https://www.npmjs.com/package/gulp-concat)

My setup for my question:

I have all my js embraced by a document.ready (I'm using jQuery). For simplicity let's say I have within this 3 functions, content does not matter. I would like to distribute those 3 functions to 3 separate .js files.

$(function() { 
    function myFunction1(){}
    function myFunction2(){}
    function myFunction3(){}
}

What I would like to have:

main.js:

$(function() { 
    // load function1.js
    // load function2.js
    // load function3.js

}

and all the separate functionX.js

By using gulp to concatenate I would like to end up with the code at the beginning (all in one file, and properly embraced by $(function() {}

Now first, I don't know how to load the functions into this, so that during development I have full functional code by just including my main.js and without concatenating. Is this even possible?

I tried to use

$.getScript("function1.js", function(){
});

but after concatenating – not to my surprise – this just remained like it was.

So is there another way of achieving this?

Or would a better option be to write 3 different functions.js, all with their own $(function() {}) and after concatenating I have that part 3 times? While I would just include all of the files during development in my html?

It would be awesome to hear your thoughts about this, and how to work with js modules while not repeating any code.

Thanks a lot.

1 个答案:

答案 0 :(得分:1)

好的,我刚刚与另一位开发人员交谈过,我们主要告诉我以下方法:

  • 使用不同的模块编写不同的.js文件(我自己的代码分离以便更好地维护)

  • 所有这些包括他们自己的立即调用函数表达式以禁止范围问题及其document.ready函数

    (function ($) { // iief = Immediately-Invoked Function Expression, mainly useful to limit scope
        $(function() { // Shorthand for $( document ).ready()
        // whatever code
        });
    }(jQuery));
    
  • 然后使用例如gulp并编写一个监视任务,以便在更改后动态连接

  • 使用concat sourcemap函数仍然可以看到正确的亚麻布等原始文件。(Sourcemaps

  • 包括all.js(连接一个)

  • 最后缩小分段和部署

  • 并使用if($('.selector').length){}检查是否应根据选择器的存在执行代码

所以,这就是我现在关注的方式。无论如何,我很想听听你的想法。 干杯