Tamas
Tamas

Reputation: 11214

Express.js routing for bower components

I have changed my Express.js project to use bower to install components. All components are installed under /components (/components/jquery/jquery.js ...etc).

I have create my own router as well which looks like this:

app.get('/', routes.index); // main page
app.get('/p/:name', routes.p); //redirect routes

app.get('/api/contacts', api.contacts); //look at all
app.get('/api/contact/:id', api.contact); //look at one
app.post('/api/contact', api.add); //add contact
app.put('/api/contact/:id', api.edit); //edit&update contact
app.delete('/api/contact/:id', api.delete); //delete contact

There are no routes for /components therefore http://my.project/components/jquery/jquery.js comes back with a Cannot GET /components/jquery/jquyery.js

Can someone please let me know what's the best way to add routing for all the components under /components?

Upvotes: 20

Views: 10413

Answers (2)

Duke
Duke

Reputation: 7444

If you use connect-assets, something like this works well:

app.use require("connect-assets")(paths: ['assets/js', 'assets/css', 'bower_components'])

Then in your js manifest you can simply include bower components like the other js assets. assets/application.js:

// bower components:
//= require jquery/dist/jquery
//= require underscore/underscore
//= require backbone/backbone
// local assets:
//= require my_app

Upvotes: 5

Pickels
Pickels

Reputation: 34630

You probably want to use the static middleware to do this. I am not familiar with bower but if all your components are install in /components then you can do the following:

app.use(express.static(__dirname + '/components'));

This means if you have /components/jquery/jquery.js you can include it with

<script src='/jquery/jquery.js'></script>

If you rather prefix it with /components you can do:

app.use('/components', express.static(__dirname + '/components'));

That way you can request the scripts with:

<script src='/components/jquery/jquery.js'></script>

Upvotes: 53

Related Questions