Copying node_modules or bower_components to static/public directory in web app

1.3k views Asked by At

I am using a Node.js Express web server - I see some people using Grunt or Gulp scripts to copy the bower_components directory into the /public directory so those assets can be requested. Is there a better way to point to bower_components or node_modules than just copying files during a build?

3

There are 3 answers

0
andyhasit On

You can always point to your bower components directly from HTML:

 <script src="bower_components/jquery/dist/jquery.min.js"></script>

The reason people advise not to do this is because you might not want to copy your whole bower directory to the production environment. But you you can always preen the bower directory and have it only include the files you need before uploading to the production server, which means you can retain the paths in HTML as above.

Or you can copy the files you need to a place in your static directory, which is the more common approach, and with gulp/grunt it isn't all that cumbersome.

There are various tools available for all these tasks, there is a good list in Bower website's tools page, which will also give you an idea of the approaches people employ for this specific problem (and have therefore built tools for).

http://bower.io/docs/tools/

0
Kunal Kapadia On

You can use multiple static assets directory.

So you can define something like this:

app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(path.join(__dirname, 'bower_components')));

Now express will first search for your requested asset in public dir if not found it will search in bower_components dir before sending 404 not found error.

0
David Douglas On

Yes you can also serve other folders like 'bower_componenets' in your Expressjs dir using:

app.use('/bower_components', express.static(path.join(__dirname, 'bower_components')));