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>
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'>
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
精彩评论