Skip to content

Instantly share code, notes, and snippets.

@yalab
Last active July 20, 2022 20:29
Show Gist options
  • Save yalab/cad361056bae02a5f45d1ace7f1d86ef to your computer and use it in GitHub Desktop.
Save yalab/cad361056bae02a5f45d1ace7f1d86ef to your computer and use it in GitHub Desktop.
rails5 + webpacker + bootstrap
$ echo 'gem "webpacker"' >> Gemfile
$ bundle install
$ rails webpacker:install
$ yarn add [email protected] jquery popper.js
diff --git a/config/webpack/environment.js b/config/webpack/environment.js
index d16d9af..86bf1a7 100644
--- a/config/webpack/environment.js
+++ b/config/webpack/environment.js
@@ -1,3 +1,10 @@
 const { environment } = require('@rails/webpacker')
 
+const webpack = require('webpack')
+environment.plugins.set('Provide', new webpack.ProvidePlugin({
+  $: 'jquery',
+  jQuery: 'jquery',
+  Popper: ['popper.js', 'default']
+}))
+
 module.exports = environment
// app/javascript/packs/bootstrap.scss
@import '~bootstrap/dist/css/bootstrap';
// app/javascript/packs/applicatoin.js
import 'bootstrap/dist/js/bootstrap';
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -6,6 +6,8 @@

     <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
     <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
+    <%= javascript_pack_tag 'application' %>
+    <%= stylesheet_pack_tag 'bootstrap' %>
   </head>

   <body>
@chibicode
Copy link

+1 on environment.plugins.append instead of environment.plugins.set. Without that, you'll end up with this error:

Webpacker can't find application.js in /public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
Your manifest contains:
{
}

@RomuloDevelop
Copy link

@iamajvillalobos thats work!. Thanks!

@mogongzi
Copy link

It works a lot better now, less code.

# Install bootstrap, jquery and popper.js
yarn add bootstrap jquery popper.js
# Create this file app/javascript/packs/src/application.scss
@import '~bootstrap/scss/bootstrap';
# Reference the new application.scss in your app/javascript/packs/application.js
import 'bootstrap'
import './src/application.scss'
# If you haven't changed it yet, use the pack_tags
<%= stylesheet_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

All is good!

Thanks, it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment