sa125
sa125

Reputation: 28971

Grunt - change asset linking when building for production

I've built a mobile version of an existing website. The site I've built is completely static and relies only on HTML/CSS/JS. This site resides on the same server as the desktop version and is served from under http://example.com/mobile as a subdirectory. As such, I've set the <base> tag to:

<base href="http://example.com/mobile/">

The only access I get to the existing site is via FTP, so I don't have too many options to reconfigure the already existing server. And I don't want to either.

My mobile version is only somewhat functioning - all the <script> and <link> tags inside index.html correctly point to http://example.com/mobile/{js,css,img}, while links used inside js or css files look up to the top domain (e.g - http://example.com/img/image.png instead of http://example.com/mobile/img/image.png).

I can manually copy all the assets for the links to work, but since this is a Grunt project I figured there might be a smarter way to do this.

So, how can I have all internal asset links in js or scss files change when building (grunt build)? Something like:

site.css

// in dev
body {
  background: url('/img/image.png') top left no-repeat;
}

// after building
body {
  background: url('/mobile/img/image.png') top left no-repeat;
}

Thanks.

Upvotes: 0

Views: 170

Answers (1)

Matthew Bakaitis
Matthew Bakaitis

Reputation: 11970

See grunt-replace or grunt-string-replace as tools that can help with this.

You could use either of these within your build task to process the changes you need.

The hardest part will be writing an accurate regex, but there are many regex testers/builders online that can help if you aren't expert at that.

Also, while .htaccess is a great idea for Apache based sites, it doesn't help if you are on Windows or on a cloud hosting solution that doesn't honor it.

Upvotes: 1

Related Questions