Henry B
Henry B

Reputation: 8047

Javascript import just for development

I come from a Java background where it's pretty common to have dependencies for testing and not for production, however, using I'm finding it hard to understand how this can be achieved with Javascript and HTML.

I really would like to be able to develop some javascript which only runs whilst I am developing (running gulp serve) and then when I run gulp those files don't get included in the dist, but I can't find any common way of doing it.

So far I'm using yeoman's gulp-webapp.

Is this something which just isn't done (having a test script that isn't included in production release), or is there some automation I'm missing to do this?

Upvotes: 0

Views: 96

Answers (2)

Henry B
Henry B

Reputation: 8047

As fate and rubber duck debugging would have it I think I've found the answer to my otherwise elusive question. Sorry for self answering, but I'm putting this here for prosperity, and so other's may learn.

The gulp script generated uses useref which means that one can put comments in the html to group together files. It also, however, gives the ability to remove those files using the following syntax:

<!-- build:remove -->
<script src="/bower_components/jquery-mockjax/jquery-mockjax.js"></script>
<script src="scripts/mock.js"></script>
<!-- endbuild -->

So now I'm just using this instead and when I do gulp serve it contains the javascript files and when I call gulp they just get removed.

Upvotes: 1

Ava
Ava

Reputation: 2429

Here are a few different solutions:

Javascript/jQuery: One way would be, as blex mentioned, to created a DEBUG_MODE boolean in a script that is loaded always, then that script would insert into the document more script nodes that would contain the scripts that it decided are good for loading.

For example:

if(DEBUG_MODE){
    for(var x=0; x<debuggingScripts.length; x++){
        InsertScript(debuggingScripts[x]);
    }
}

Where debuggingScripts would be an array of script URLs, and InsertScript() would be a method adding the script to the DOM.

Python/Cleaning Script: Another way, that I personally have used, would be to have a script that automatically generates a "Production" version of your webpage. For example, I have a Python script that will ignore any code in my development HTML files that is wrapped within a <!--ignore--> and <!--endignore--> comments. When I run the Script, it generates and packages the newest "Release" version of my code without any of the ignored code which is present in the testing enviroment.

PHP: You could also do a similar thing with PHP (or any other preprocessor/serverside script), where the PHP that generates your header would ignore certain javascript URLs in a certain array or however you would format it.

Hopefully one of these helps you! If you need more example code than I gave, also let me know, I'd be happy to write up an example script.

Upvotes: 0

Related Questions