wilsonpage
wilsonpage

Reputation: 17610

NodeJS/ExpressJS: Serving single concatenated JS file in production

I am working with lots of individual JS files served like so:

<script defer src="/js/libs/jquery.min.js"></script>
<script defer src="/js/libs/plugins.js"></script>

<!-- application core -->
<script defer src="/js/application.js"></script>

<!-- modules -->
<script defer src="/js/modules/router.js"></script>
<script defer src="/js/modules/feed.js"></script>
<script defer src="/js/modules/files.js"></script>
<script defer src="/js/modules/members.js"></script>
<script defer src="/js/modules/sharebar.js"></script>
<script defer src="/js/modules/utils.js"></script>

In production I use connect-assetmanager to concatenate all these files into one script.js. How can I dynamically alter my site layout.jade to serve this single JS file like so?

<script defer src="/js/script.js"></script>

Upvotes: 2

Views: 872

Answers (2)

wilsonpage
wilsonpage

Reputation: 17610

I ended up using RequireJS as with it's optimisation features you can build a single JS file (main.js) for production. In development all files are separate JS files which get loaded asynchronously and in production these files are concatenated into one big js file.

The main point is that the <head> part of your page (or wherever you load your scripts) remains the same in production and development.

<script data-main='/js/main.js' src='/js/plugins/require.js'>

Upvotes: 2

Peter Lyons
Peter Lyons

Reputation: 145994

Why bother behaving differently between production/development for this? It will probably bite you in the ass eventually and AFAICT connect-assetmanager doesn't really add any hindrance to the development cycle, so just use it all the time and don't worry about it.

However, if you must, its just a matter of looking at the process.env['NODE_ENV'] value and a conditional clause in your layout.jade.

if production
  script(src="/js/script.js")
else
  script(src="/js/libs/jquery.min.js")
  script(src="/js/libs/plugins.js")
  #and so so

Upvotes: 1

Related Questions