• Stars
    star
    1,025
  • Rank 44,923 (Top 0.9 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Load Bootstrap styles and scripts in your Webpack bundle

Build Status npm version

Webpack v4 and Bootstrap v4 supported!

If you're using this project and you like it, please give us a star! Thanks!

If you're building an e-commerce site, like printivity.com or a marketplace site like datacenters.com and Hawaii Chee, and you want to use Rails and React, please get in touch, as that is ShakaCode's speciality. We built those sites!

Intersted in optimizing your webpack setup for React on Rails including code splitting with react-router v4, webpack v4, and react-loadable? Contact me.

ShakaCode is currently looking to hire like-minded developers that wish to work on our projects, including Hawaii Chee. We're getting into Reason!

We at ShakaCode are a small, boutique, remote-first application development company. We fund this project by:

  • Providing priority support and training for anything related to React + Webpack + Rails in our Coaching Program.
  • Building custom web and mobile (React Native) applications. We typically work with a technical founder or CTO and instantly provide a full development team including designers.
  • Migrating Angular + Rails to React + Rails. You can see an example of React on Rails and our work converting Angular to React on Rails at egghead.io.
  • React on Rails is ShakaCode's flagship product. We want to make sure you're aware of it!

Aloha and best wishes from the ShakaCode team!

ShakaCode Community

2017-01-31_14-16-56

Testimonials

From Joel Hooks, Co-Founder, Chief Nerd at egghead.io, January 30, 2017: 2017-01-30_11-33-59

bootstrap-loader v3 Docs!

If you want the v1 docs which are compatible with Webpack v1, please see the v1 branch. If you're using v2, be sure to check the peer dependencies of webpack and the extract-text-webpack-plugin. See the v2 docs.

bootstrap-loader

Successor to bootstrap-sass-loader. Load Bootstrap styles and scripts in your Webpack bundle. This loader uses SASS to process CSS styles. Bootstrap 3 & 4 are supported.

Table of Contents

Installation

Get it via npm:

npm install bootstrap-loader

Don't forget to install these dependencies (use --save or --save-dev option per your needs to update your package.json):

# Bootstrap 3
npm install --save-dev bootstrap-sass

# or Bootstrap 4
npm install --save-dev bootstrap

# Node SASS & other loaders needed to handle styles
npm install --save-dev css-loader node-sass resolve-url-loader sass-loader style-loader url-loader

# Additional loaders required for Bootstrap 3 & 4
npm install --save-dev imports-loader exports-loader

If you're using Bootstrap 4, you probably need:

npm install --save-dev postcss-loader

Usage

Simply require it:

require('bootstrap-loader');

Or add bootstrap-loader as a module in an entry point in your webpack config (you'll need Webpack 2.1 beta and higher):

entry: [ 'bootstrap-loader', './app' ]

Config is optional. If used, by default it should be placed in your project's root dir with name .bootstraprc. You can write it in YAML or JSON formats. Take a look at the default config files for Bootstrap 3 and Bootstrap 4. Note, we recommend using a configuration or else you might pick up unwanted upgrades, such as when we make Bootstrap 4 the default. Config options don't fall back on the defaults once a config file is present. Be sure not to delete config options. To start with a custom config, copy over a default config file as a starting point.

If the default location doesn't work for you (e.g. you want to create multiple bootstrap configs for branding variations or you symlink your npm_modules directory), you may pass the absolute path of the .bootstraprc file to the loader in your webpack config, e.g. bootstrap-loader/lib/bootstrap.loader?extractStyles&configFilePath=${__dirname}/.bootstraprc!bootstrap-loader/no-op.js.

Note that :__dirname is a global variable that Node sets for us. It is "the name of the directory that the currently executing script resides in."

YAML Format

---
# You can use comments here
styleLoaders:
  - style-loader
  - css-loader
  - sass-loader

styles:
  normalize: true
  print: true

scripts:
  alert: true
  button: true

JSON Format

{
  // And JSON comments also!
  "styleLoaders": ["style-loader", "css-loader", "sass-loader"],

  "styles": {
    "normalize": true,
    "print": true
  },

  "scripts": {
    "alert": true,
    "button": true
  }
}

If no config provided, default one for Bootstrap 3 will be used.

ENV Specific Values

The following settings can be set differently

Different settings for different environments can be used.

Example of setting production to extract styles and other envs don't and use the style-loader:

# It depends on value of NODE_ENV environment variable
env:
  production:
    extractStyles: true
    styleLoaders:
      - css-loader
      - postcss-loader
      - sass-loader

# If NODE_ENV specific value not found
extractStyles: false
styleLoaders:
  - style-loader
  - css-loader
  - postcss-loader
  - sass-loader

Bootstrap 4 internal dependency solution

Because of Bootstrap 4's removal of UMD, internal dependencies, such as Popover's dependencies on Tooltip and Dropdown's dependency on Utils, are no longer naively resolved by Webpack (See Issue #172. In order to solve this issue, add the following code to your webpack configuration:

plugins: [
  new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    "window.jQuery": "jquery",
    Tether: "tether",
    "window.Tether": "tether",
    Popper: ['popper.js', 'default'],
    Alert: "exports-loader?Alert!bootstrap/js/dist/alert",
    Button: "exports-loader?Button!bootstrap/js/dist/button",
    Carousel: "exports-loader?Carousel!bootstrap/js/dist/carousel",
    Collapse: "exports-loader?Collapse!bootstrap/js/dist/collapse",
    Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown",
    Modal: "exports-loader?Modal!bootstrap/js/dist/modal",
    Popover: "exports-loader?Popover!bootstrap/js/dist/popover",
    Scrollspy: "exports-loader?Scrollspy!bootstrap/js/dist/scrollspy",
    Tab: "exports-loader?Tab!bootstrap/js/dist/tab",
    Tooltip: "exports-loader?Tooltip!bootstrap/js/dist/tooltip",
    Util: "exports-loader?Util!bootstrap/js/dist/util",
  })
]

Examples

Check out example apps in examples/ folder:

Common configuration options

Here are common options for Bootstrap 3 & 4.

Bootstrap 3 & 4

loglevel

Default: disabled

Outputs debugging info. Set this option to debug to output debugging information. This is critical for debugging issues. The output will go to your webpack console.

loglevel: debug

bootstrapVersion

Default: 3

Major version of Bootstrap. Can be 3 or 4.

bootstrapVersion: 3

styleLoaders

Default: [ 'style-loader', 'css-loader', 'sass-loader' ] Env Specific: true

Array of webpack loaders. sass-loader is required, order matters. In most cases the style loader should definitely go first and the sass loader should be last.

Note: Beginning with Webpack v2.1.0-beta.26, the '-loader' suffix is required for all loaders. To maintain compatibility with older versions, all accepted style loaders (style, css, postcss, sass, resolve-url) are automatically appended with '-loader'. It is recommended that you explicitly state the '-loader' suffix for every webpack loader in styleLoaders to ensure compatibility in the long term.

styleLoaders:
  - style-loader
  - css-loader
  - sass-loader

# You can apply loader params here:
  - sass-loader?outputStyle=expanded

Different settings for different environments can be used. See above example.

extractStyles

Default: false Env Specific: true

Extract styles to stand-alone css file using mini-css-extract-plugin version 2.0.0-beta or higher. See mini-css-extract-plugin for more details.

extractStyles: false

Different settings for different environments can be used. See above example.

This param can also be set to true in webpack config:

entry: [ 'bootstrap-loader/extractStyles', './app' ]

See shakacode/react-webpack-rails-tutorial/blob/master/client/webpack.client.rails.build.config. for a working example which is deployed to www.reactrails.com.

preBootstrapCustomizations

Default: disabled

Customize Bootstrap variables that get imported before the original Bootstrap variables. Thus, derived Bootstrap variables can depend on values from here. See the Bootstrap _variables.scss file for examples of derived Bootstrap variables.

preBootstrapCustomizations: ./path/to/bootstrap/pre-customizations.scss

bootstrapCustomizations

Default: disabled

This gets loaded after bootstrap variables is loaded. Thus, you may customize Bootstrap variables based on the values established in the Bootstrap _variables.scss file. Note, if bootstrap did not have derived values, it would not be necessary to have two config files for customizing bootstrap values.

If you want your bootstrap override value to apply to derived variable values, then place your customizations in preBootstrapCustomizations. If you want to be sure your changes don't affect other derived values, place the changes in bootstrapCustomizations.

If you are not sure, you can probably simply use preBootstrapCustomizations and, if you have issues, see _variables.scss for derived values.

bootstrapCustomizations: ./path/to/bootstrap/customizations.scss

appStyles

Default: disabled

Import your custom styles here. Usually this endpoint-file contains list of @imports of your application styles.

appStyles: ./path/to/your/app/styles/endpoint.scss

styles

Default: all

Bootstrap styles.

styles:
  mixins: true
  normalize: true
  ...

# or enable/disable all of them:
styles: true / false

scripts

Default: all

Bootstrap scripts.

scripts:
  transition: true
  alert: true
  ...

# or enable/disable all of them:
scripts: true / false

useCustomIconFontPath

Default: false

If you're using a custom icon font and you need to specify its path ($icon-font-path) in your Sass files, set this option to true.

useCustomIconFontPath: true / false
$icon-font-path: ../fonts // relative to your Sass file
$icon-font-name: 'glyphicons' // you'll typically want to change this too.

Bootstrap 4 only

There is only one additional option for Bootstrap 4:

Tether

Additionally, Bootstrap 4 requires Tether. You can add Tether per the examples in the /examples directory.

  1. Add tether to package.json: npm i --save tether
  2. Add tether as an entry point to your webpack config.
  3. Add this plugin to your webpack config:
  plugins: [
    new ExtractTextPlugin('app.css', { allChunks: true }),
    new webpack.ProvidePlugin({
      "window.Tether": "tether"
    }),
  ],

PostCSS

Bootstrap 4 seems to require postcss:

  1. Add postcss and the the postcss-loader: npm i --save postcss postcss-loader
  2. Put postcss before sass in the order of loaders in your .bootstraprc file.

Glyphicon alternatives

Glyphicons have been removed from Bootstrap 4. The examples demonstrate how to use the font-awesome-loader

Additional configurations

Paths to custom assets

If you use bootstrap-loader to load your styles (via preBootstrapCustomizations, bootstrapCustomizations & appStyles) and you load custom assets (fonts, images etc.), then you can use relative paths inside url method (relative to SASS file, from which you load asset).

This was made possible thanks to resolve-url-loader. In common case you don't have to do anything special to apply it — we are doing it internally (just don't forget to install it). But if you want to use its custom settings, please provide it explicitly via styleLoaders option in .bootstraprc:

styleLoaders:
  - style-loader
  - css-loader?sourceMap
  - resolve-url-loader?sourceMap
  - sass-loader?sourceMap

Incorporating Bootswatch themes

The following steps are needed to successfully incorporate a theme from Bootswatch:

  1. Download the .scss files (_variables.scss and _bootswatch.scss) for the theme you have chosen.

  2. Put the files somewhere in your project structure (e.g. the ./styles directory).

  3. Add an additional SCSS file, like bs-theme.scss, that contains the following:

    @import './_bootswatch.scss';
    
  4. Add the following to your .bootstraprc file:

preBootstrapCustomizations: ./styles/_variables.scss
appStyles: ./styles/bs-theme.scss

The theme should now be applied as expected. Note that this section might be valid for other theme packs as well.

Multiple CSS themes

See examples/multiple-entries/webpack.prod.config.js for an example configuration of the following:

  1. In entry, set up one bundle per theme. In each bundle include bootstrap-loader with extractStyles and the respective config file.
  2. In plugins, set up the extract-text-webpack-plugin to output each CSS file as [name].css. This will output a CSS file named after each bundle.

jQuery

If you want to use Bootstrap's JS scripts — you have to provide jQuery to Bootstrap JS modules using imports-loader. To avoid having to include jQuery in your project you can disable all scripts (see scripts).

module: {
  loaders: [
    // Use one of these to serve jQuery for Bootstrap scripts:

    // Bootstrap 3
    { test:/bootstrap-sass[\/\\]assets[\/\\]javascripts[\/\\]/, loader: 'imports-loader?jQuery=jquery' },

    // Bootstrap 4
    { test: /bootstrap[\/\\]dist[\/\\]js[\/\\]umd[\/\\]/, loader: 'imports-loader?jQuery=jquery' },
  ],
},

Note: if you're not concerned about Windows, the lines look like this (simpler regexp pattern):

// Bootstrap 3
{ test: /bootstrap-sass\/assets\/javascripts\//, loader: 'imports-loader?jQuery=jquery' },

// Bootstrap 4
{ test: /bootstrap\/dist\/js\/umd\//, loader: 'imports-loader?jQuery=jquery' },

Icon fonts

Bootstrap uses icon fonts. If you want to load them, don't forget to setup url-loader or file-loader in webpack config:

module: {
  loaders: [
    { test: /\.(woff2?|svg)$/, loader: 'url-loader?limit=10000' },
    { test: /\.(ttf|eot)$/, loader: 'file-loader' },
  ],
},

FAQ

Using Bootstrap mixins and variables

You should use sass-resources-loader in your webpack config.

In your webpack.config.js:

module.exports = {

  // stuff removed for clarity ...

  module: {
    loaders: [
      // stuff removed for clarity ...
      {
        test: /\.scss$/,
        loader: ExtractTextPlugin.extract(
          'style-loader',
          'css-loader?modules&importLoaders=2&localIdentName=[name]__[local]__[hash:base64:5]' +
          '!sass-loader' +
          '!sass-resources-loader'
        ),
      },
      // stuff removed for clarity ...
    ],
  },

  // stuff removed for clarity ...

  sassResources: './config/sass-resources.scss',
}

And in your ./config/sass-resources.scss:

// Make variables and mixins available when using CSS modules.
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap/_variables";
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap/_mixins";

You can then use mixins and variables from Bootstrap in your own code.

Using a custom location for bootstrap module

By default, bootstrap-loader will try to resolve bootstrap from where bootstrap-loader has been installed. In certain situations (e.g. npm linking, using a custom package installer) it may not be resolvable. In this case, you can pass in the location manually.

require('bootstrap-loader?bootstrapPath=/path/to/bootstrap');

// or

entry: [ 'bootstrap-loader?bootstrapPath=/path/to/bootstrap', './app' ]

Contributing

See Contributing to get started.

License

MIT.

Examples and related libraries

Useful Q&A

We'll identify issues that are questions.


Thank you from Justin Gordon and ShakaCode

The ShakaCode team has availability to help your project. If your team might need my help, please email me for a free half-hour project consultation, on anything from React on Rails to any aspect of web or mobile application development for both consumer and enterprise products.

We at ShakaCode are a small, boutique, remote-first application development company. We fund this project by:

  • Providing priority support and training for anything related to React + Webpack + Rails in our Coaching Program.
  • Building custom web and mobile (React Native) applications. We typically work with a technical founder or CTO and instantly provide a full development team including designers.
  • Migrating Angular + Rails to React + Rails. You can see an example of React on Rails and our work converting Angular to React on Rails at egghead.io.
  • Augmenting your team to get your product completed more efficiently and quickly.

I appreciate your attention and sharing of these offerings with anybody that we can help. Your support allows me to bring you and your team front-end happiness in the Rails world.

Aloha and best wishes from the ShakaCode team!

Supporters

JetBrains ScoutAPM
BrowserStack Rails Autoscale Honeybadger Reviewable

The following companies support our open source projects, and ShakaCode uses their products!

More Repositories

1

react_on_rails

Integration of React + Webpack + Rails + rails/webpacker including server-side rendering of React, enabling a better developer experience and faster client performance.
Ruby
5,085
star
2

react-webpack-rails-tutorial

Example of integration of Rails, react, redux, using the react_on_rails gem, webpack, enabling the es7 and jsx transpilers, and node integration. And React Native! Live Demo:
Ruby
1,717
star
3

sass-resources-loader

SASS resources (e.g. variables, mixins etc.) loader for Webpack. Also works with less, post-css, etc.
JavaScript
981
star
4

cypress-on-rails

Use cypress.io or playwright.dev with your rails application. This Ruby gem lets you use your regular Rails test setup and clean-up, such as FactoryBot.
HTML
414
star
5

shakapacker

Use Webpack to manage app-like JavaScript modules in Rails
Ruby
410
star
6

fat-code-refactoring-techniques

Code samples for RailsConf 2014 on Fat Code Refactoring
JavaScript
289
star
7

re-formality

Form validation tool for reason-react
Reason
244
star
8

bootstrap-sass-loader

Webpack Loader for the Sass version Twitter Bootstrap
JavaScript
118
star
9

rescript-dnd

Drag-n-drop for @rescript/react
ReScript
115
star
10

rescript-classnames

Reimplementation of classnames in ReScript
ReScript
110
star
11

rescript-logger

Logging implementation for ReScript
ReScript
107
star
12

react_on_rails_demo_ssr_hmr

react_on_rails tutorial demonstrating SSR, HMR fast refresh, and Typescript based on the rails/webpacker webpack setup
Ruby
88
star
13

steward

Task runner and process manager for Rust
Rust
49
star
14

font-awesome-loader

Webpack Loader for Font Awesome Using Sass
JavaScript
47
star
15

webpacker_lite

Slimmed down version of Webpacker with only the asset helpers optimized for, but not requiring, React on Rails
Ruby
46
star
16

rescript-debounce

Debounce for ReScript
ReScript
43
star
17

mirror-creator

One more way to create an object with values equal to its key names
JavaScript
43
star
18

control-plane-flow

The power of Kubernetes with the ease of Heroku! Our playbook for migrating from Heroku to Control Plane, controlplane.com, and CPL CLI source
Ruby
43
star
19

reactrails-react-native-client

This repository is for a react-native client to the https://www.reactrails.com/, source at https://github.com/shakacode/react-webpack-rails-tutorial/.
JavaScript
30
star
20

redux-tree

An alternative way to compose Redux reducers
JavaScript
23
star
21

messagebus

Message bus - enables async communication between different parts of application using messages
Rust
23
star
22

rust-rescript-demo

Rust
22
star
23

ssr-rs

Server-Side Rendering for Rust web servers using Node.js
Rust
20
star
24

redux-interactions

Composing UI as a set of interactions
20
star
25

bootstrap-sass-loader-example

Example of using the bootstrap-sass-loder to load the Sass version of Twitter Bootstrap using Webpack
JavaScript
16
star
26

style-guide-javascript

ShakaCode's JavaScript Style Guide (Also see our Ruby one: https://github.com/shakacode/style-guide-ruby)
JavaScript
15
star
27

jstreamer

Ruby
12
star
28

justerror

Extension to `thiserror` that helps reduce the amount of handwriting
Rust
12
star
29

react-validation-layer

An opinionated form validation tool for React apps
JavaScript
11
star
30

rescript-react-on-rails

BuckleScript bindings to react-on-rails
ReScript
8
star
31

todos-react-native-redux

Todos app with React Native and Redux
JavaScript
7
star
32

rescript-react-on-rails-example

Example of https://rescript-lang.org/ with React on Rails
Ruby
7
star
33

conform

Macro to transform struct string fields in place
Rust
7
star
34

package_json

Ruby
6
star
35

rescript-throttle

Throttle for ReScript
ReScript
6
star
36

rescript-first-class-modules-usage

CSS
6
star
37

webpacker-examples

Ruby
5
star
38

react_on_rails-with-webpacker

Prototype of webpacker integration
Ruby
4
star
39

use-ssr-computation.macro

A babel macro for reducing initial bundle-size of Apps with React SSR. Uses conditional compilation to make computations server-side and pass the results to the client.
TypeScript
4
star
40

react_on_rails-generator-results

Results of running different react_on_rails generators. See https://github.com/shakacode/react_on_rails
4
star
41

vosk-rs

Rust
3
star
42

react-starter-kit-with-bootstrap-loader

JavaScript
3
star
43

uber_task

Ruby
3
star
44

react_on_rails-generator-results-pre-0

Ruby
2
star
45

js-promises-testing

JavaScript
2
star
46

react-on-rails-demo

Example of using the generator for React on Rails
Ruby
2
star
47

node-webpack-async-example

Simple example of setting up node with webpack
JavaScript
2
star
48

egghead-add-redux-component-to-react-on-rails

Source for Egghead lesson: Add Redux State Management to a React on Rails Project
Ruby
1
star
49

reactrails-in-reagent

Test of converting reactrails example to reagent
1
star
50

.github

1
star
51

rails-tutorial-with-react-on-rails

Adding React on Rails to the Rails Tutorial
Ruby
1
star
52

react_on_rails-test-new-redux-generation

Testing out a different redux generation. See https://github.com/shakacode/react_on_rails/pull/584
Ruby
1
star
53

yardi

Yet Another Rust Dependency Injector
Rust
1
star
54

old-react-on-rails-examples

Various example apps for React on Rails, outdated
JavaScript
1
star
55

v8-demo

React on Rails v8 Usage of the basic generator and a "generator function example"
Ruby
1
star
56

docker-ci

docker container that runs all test and linting against app
Ruby
1
star
57

react-rails-webpacker-resources

1
star
58

sass-rel-paths-issue

JavaScript
1
star
59

reactrails-in-om-next-example

Test of converting reactrails example to om-next
1
star
60

homebrew-brew

Ruby
1
star
61

zone-helper

Swift
1
star
62

react_on_rails-update-webpack-v2

Updating the default React on Rails 6.6.0 redux installation to use Webpack v2 plus adding eslint.
Ruby
1
star
63

shakacode-website

Public website and blog
HTML
1
star
64

react-native-image-zoom-slider

JavaScript
1
star
65

derive-from-one

Automatically generates `From` impls so you don't have to
Rust
1
star
66

rescript-on-rails-example

A sample application using Rescript and React on Rails.
Ruby
1
star