简体   繁体   中英

How can I concatenate javascript files and replace the reference in my HTML?

As part of my build/CI process on TeamCity, I would like to specify a set of JavaScript files referenced in my HTML and combine them into one.

In other words, this is what I would like to accomplish.

Before:

<script src="1.js" />
<script src="2.js" />

After

<script src="combined.js" />

I am looking for a commandline tool to concatenate 1.js and 2.js into combined.js. Then, a commandline tool (or maybe the same tool) to replace the references in the HTML file to this new file. Please tell me how I could accomplish this.

What I have tried so far:

I have been looking at grunt-usemin which looks good, but requires the build server to perform an npm install on each build to get the dependencies, then run it. That takes too long and isn't a nice solution, because we build+deploy very frequently.

I know I could also add my node_modules folder to git but this is also undesirable. It would be nice if grunt could run these modules installed globally but it is not the grunt way (unless I am mistaken, grunt wants everything installed locally).

Someone also suggested running grunt on the developer machines. Again, undesirable as we have transient VMs and this would break the development flow.

It would be nice if I could run grunt-usemin locally without grunt!

For combining the files you can just use cat

cat 1.js 2.js > combined.js

To replace the chunk of html you could use sed

sed -i "s/<script src=\"1.js\">\n<script src=\"2.js\">/<script src=\"combined.js\">/g" *.html

This is a rather general solution, but it seems a bit clunky to me. If you're rendering this html in node you might consider replacing it in javascript if the combined file exists.

if (fs.existsSync('combined.js')) {
    res.end(html_contents.replace('<script src="1.js"/>\n<script src="2.js"/>','<script src="combined.js">'));
} else {
    res.end(html_contents);
}

for better performance you can of course use the asynchronous version of fs.exists

I ended up creating my own: https://npmjs.org/package/hashcat

npm install -g hashcat

@gustavohenke's recommendation was close but ultimately h5bp was proving to be too problematic for use on a build server. Ultimately creating this module did not take long and serves my needs for now. I will mark this as the answer until a better answer comes along in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM