How to include css and js files in Node.js project - node.js

What is the correct way to include css and js files in express project ?
I am using ejs template engine. I have seen one example using connect-assetmanager but it was difficult to follow.
A small example project which includes css and js in index.ejs (not layout.ejs) would be very useful.

Static files can be served with express' static middleware. I usually make a directory for all static files to be served from the root.
If you've installed express globally with npm (npm install -g express) you can type the following at the command line.
express <project_name>
This will create a small example project for you. This example project has a folder named public, from which it serves static files. It further contains folders named javascripts and stylesheets.
The relevant piece of the example project for setting this up is the following line in the file app.js in the function passed to app.configure.
app.use(express.static(path.join(__dirname, 'public')));
Example is from express 3.0.0rc1
Express is built on Connect. The docs for it's static middleware might be helpful: Connect : Static

Related

mdBootStrap and NodeJS Directory Structure Inquiry

I've read over the documentation and I cannot seem to find a clear answer as to the proper directory structure for a node application (insert downvotes here).
When I create an application directory off the root. All js, css, and img directories will be based of this application directory. My confusion comes in where when I install mdBootStrap using npm it creates the node_modules and mdbootstrap directory as expected, but then down these chains of directories it creates it's own js and css directory as well.
So back in the main application directory, in the HTML files, when I reference bootstrap and jquery files for example, am I forced to reference all the way down the node_modules directory, or has the mdBootStrap actually become my new application directory.
If you are using express you can expose your node_modules dependancy folder through your routing by adding a static route.
var application = express();
application.use('/mdbootstrap', express.static(__dirname + '/node_modules/mdbootstrap'));
Other options are using gulp build tasks to include the node_module dependancies in your output build.

Add custom js file to JHipster

I'm trying to include a javascript file which is not available as bower.
So I copied it to src/main/webapp/content and referenced in index.html
In the DEV profile all is fine -- it works.
Now, after generating WAR file with the PROD profile, the custom.js file is not included in the WAR (tried to unpack -- file is not there).
I have discovered the gulp is merging all css and js files, did I miss a config for this?
When the app is loaded, the browser complains with 404 in the index.html -- js file not found.
How can I fix this? What is the right way to include JS (or CSS) file into JHipster app?
Thank you.
JS are not expected to be in content folder.
For CSS, copy your file to src/main/webapp/content/css.
For JS, copy your file to src/main/webapp/app possibly in a dedicated sub folder.
You don't have to inject them in index.html, gulp will do it for you. I suppose you did not see it in dev profile because you were not running gulp serve as explained in the doc

Getting start with Node, Express, and Bootstrap

I've started reading up on Node and Express with the intention of porting a few projects of mine over to it. The projects I'm porting are currently built with Python and Flask, and styled with Bootstrap.
I'm having difficulties getting a basic Express site up and running with Bootstrap as the styling. I used express-generator to get the basic skeleton set up, and then used npm to install bootstrap:
npm install bootstrap
I added bootstrap as a requirement, and as a middleware:
var bootstrap = require('bootstrap');
app.use('bootstrap');
Now I'm just not sure how to "import" that into my layout template. If someone could show me an example, or point me to a resource, that'd be great.
Nodejs is used on the backend there is no need to npm install bootstrap. Node will serve your html or jade/pug/ejs etc.
You can use a CDN and link the files in the html or pug. You can also choose to include the CSS and JS files required for bootstrap in the /public directory.
Using the Express generator is a great start, you can specify your templating engine (i.e. jade/pug, ejs etc.) or just use html. Jade/Pug will compile into HTML and be served to the front end (client side). You can include the CDN link within your jade/pug file, similar to how you would include it in regular HTML. You might want to read some documentation for pug/jade since it has a more minimalistic syntax than html, Pug Docs.
To use pug/jade enter the following command (provided you have express generator npm installed already):
express --pug --css
To use html only enter the following command (provided you have express generator npm installed already):
express --no-view --css
The commands above will create the template, all you have to do is include the CDN link within the /view/layout.pug file and you can use bootstrap. Basic routing has been defined, just npm install, and npm start.
You do not need bootstrap as a node module since bootstrap is a front end thing. You'd be better off doing a bower.
Goto your terminal
sudo npm install bower -g
Then, once you have that make a .bowerrc file
nano .bowerrc
set the default directory as public in that file
{
"directory":"./public"
}
Then, finally, do this-
bower install bootstrap --save
That will fetch bootstrap for your styles. If you want to pass data from the server to the htmls, try one of the templating engines like ejs or jade and then later add the cols in there to be rendered as html to the client.

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

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?
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/
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')));
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.

Purpose of installing Twitter Bootstrap through npm?

Question 1:
What exactly is the purpose of installing Twitter Bootstrap through npm? I thought npm was meant for server side modules. Is it faster to serve the bootstrap files yourself than using a CDN?
Question 2:
If I were to npm install Bootstrap, how would I point to the bootstrap.js and bootstrap.css files?
If you NPM those modules you can serve them using static redirect.
First install the packages:
npm install jquery
npm install bootstrap
Then on the server.js:
var express = require('express');
var app = express();
// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap
Then, finally, at the .html:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.
Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.
The point of using CDN is that it is faster, first of all, because it is a distributed network, but secondly, because the static files are being cached by the browsers and chances are high that, for example, the CDN's jquery library that your site uses had already been downloaded by the user's browser, and therefore the file had been cached, and therefore no unnecessary download is taking place. That being said, it is still a good idea to provide a fallback.
Now, the point of bootstrap's npm package
is that it provides bootstrap's javascript file as a module. As has been mentioned above, this makes it possible to require it using browserify, which is the most likely use case and, as I understand it, the main reason for bootstrap being published on npm.
How to use it
Imagine the following project structure:
project
|-- node_modules
|-- public
| |-- css
| |-- img
| |-- js
| |-- index.html
|-- package.json
In your index.html you can reference both css and js files like this:
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
Which is the simplest way, and correct for the .css files. But it is much better to include the bootstrap.js file like this somewhere in your public/js/*.js files:
var bootstrap = require('bootstrap');
And you include this code only in those javascript files where you actually need bootstrap.js. Browserify takes care of including this file for you.
Now, the drawback is that you now have your front-end files as node_modules dependencies, and the node_modules folder is usually not checked in with git. I think this is the most controversial part, with many opinions and solutions.
UPDATE March 2017
Almost two years have passed since I wrote this answer and an update is in place.
Now the generally accepted way is to use a bundler like webpack (or another bundler of choice) to bundle all your assets in a build step.
Firstly, it allows you to use commonjs syntax just like browserify, so to include bootstrap js code in your project you do the same:
const bootstrap = require('bootstrap');
As for the css files, webpack has so called "loaders". They allow you write this in your js code:
require('bootstrap/dist/css/bootstrap.css');
and the css files will be "magically" included in your build.
They will be dynamically added as <style /> tags when your app runs, but you can configure webpack to export them as a separate css file. You can read more about that in webpack's documentation.
In conclusion.
You should "bundle" your app code with a bundler
You shouldn't commit neither node_modules nor the dynamically built files to git. You can add a build script to npm which should be used to deploy files on server. Anyway, this can be done in different ways depending on your preferred build process.
Answer 1:
Downloading bootstrap through npm (or bower) permits you to gain some latency time. Instead of getting a remote resource, you get a local one, it's quicker, except if you use a cdn (check below answer)
"npm" was originally to get Node Module, but with the essort of the Javascript language (and the advent of browserify), it has a bit grown up. In fact, you can even download AngularJS on npm, that is not a server side framework. Browserify permits you to use AMD/RequireJS/CommonJS on client side so node modules can be used on client side.
Answer 2:
If you npm install bootstrap (if you dont use a particular grunt or gulp file to move to a dist folder), your bootstrap will be located in "./node_modules/bootstrap/bootstrap.min.css" if I m not wrong.
Use npm/bower to install bootstrap if you want to recompile it/change less files/test. With grunt it would be easier to do this, as shown on http://getbootstrap.com/getting-started/#grunt.
If you only want to add precompiled libraries feel free to manually include files to project.
No, you have to do this by yourself or use separate grunt tool. For example 'grunt-contrib-concat' How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

Resources