Shpigford
Shpigford

Reputation: 25378

Link directly to compiled resource in asset pipeline?

I have a script that's basically a "widget" that users embed.

It's got just simple vanilla javascript and doesn't have any require's to other resources. It's located at /app/assets/javascripts/delivery.js

What I want to do is have the file get compressed/compiled and then let users link directly to it from a script tag, ie. <script src="http://example.com/assets/delivery.js"></script>

But right now...that's a no-go. That file doesn't exist in production.

So, how can I compress that file like any other JS file in the pipeline, and then link directly to it?

Upvotes: 1

Views: 597

Answers (2)

moonfly
moonfly

Reputation: 1820

First, make sure that your app/assets/javascripts/delivery.js is not among the includes of your top-level "manifest" javascript file, i.e. app/assets/javascripts/application.js. application.js usually includes //= require_tree ., so it includes your delivery.js by default. You need to change that. Replace "require_tree" with individual "require" statements for all your assets that you want to have precompiled and combined in the application.js.

Next, update your environment files (config/environments/production.rb for production env) to include your file in the list of precompiled assets:

config.assets.precompile += %w( delivery.js )

Now you'll have it as a separate file in your public/assets directory, compiled and compressed in the same way as application.js. Just keep in mind that it has a digest attached to it's name similarly to your application.js (unless, of course, you serve the files without digests by setting config.assets.digest = false).

Upvotes: 0

Frederick Cheung
Frederick Cheung

Reputation: 84182

If you add

 config.assets.precompile += ['delivery.js']

to your application.rb, then delivery.js will be treated as a manifest file: it will be precompiled and served up as delivery.js in production. Manifest files are often just a series of //= require (or //= require_directory) statements, but any javascript they contain will also be added to the generated file.

By default the application.js manifest includes everything - you way want to tweak this so that it doesn't include javascript which is intended only to be served standalone.

Upvotes: 3

Related Questions