Add Bootstrap to your SailsJS App

In the previous post we created an empty Sails app, however with this you don’t get all the libraries loaded for free, you’ll need to add them yourself. When looking into this there were a fair few methods I tried and always came back to the same one… adding to the dependencies folder under App -> Assets.

I’ve tried a few different ways including using bower however it didn’t seem to play nicely and does bring with it a lot of baggage so I prefer to just use a grunt task to copy packages over from the modules folder.

First off you need to install boostrap

$ npm install bootstrap --save

Then we need to tell grunt to copy over the bootstrap files so we can use them in the front end, we’ll do that in the copy.js file.

// tasks/config/copy.js

// The following copies the bootstrap files from the node_modules folder to 
// the vendor/bootstrap folder in the assets directory.
// You need to do this for bot the css and js files
dev: {
      files: [
        ...
        {
          expand: true,
          cwd: './node_modules',
          src: ['bootstrap/dist/css/bootstrap.*'],
          dest: './assets/dependencies',
          flatten: false
        },
        {
          expand: true,
          cwd: './node_modules',
          src: ['bootstrap/dist/js/bootstrap.*',
          dest: './assets/dependencies',
          flatten: false
        },
      ]

Once we’ve done this we just need to add them to the asset pipeline

// tasks/pipeline.js

var cssFilesToInject = [

  'dependencies/bootstrap/dist/css/**/*.css',
  'dependencies/**/*.css',
  // Add the line below to pull in all css files from the vendor folder
  'vendor/**/*.css',
...

var jsFilesToInject = [

  'dependencies/bootstrap/dist/js/bootstrap.js',
  'dependencies/**/*.js',
  // Do the same for the js files
  'vendor/**/*.js',
...

If you load the a new page you should see bootstrap loaded nicely into the front end.

So that’s bootstrap sorted, we’ll load Parasails in the next post and we’ll be well on our way.