LoginSignup
29
26

More than 3 years have passed since last update.

Rails6のWebpackにjQueryとBootstrapを導入する手順

Posted at

Rails6からWebpackが標準導入されるようになりました。
今までjQueryやBootstrapを導入するには、それぞれのGemをインストールしてapp/assets/javascripts/application.jsapp/assets/stylesheets/application.scssで呼び出すという手順でしたが、これからはWebpackを使って管理していくのが正しい道のようです。

前提

Rails6を使っている想定なので、Webpackerのインストール手順は省略します。

諸々のインストール

以下のコマンドでインストールします。

$ yarn add bootstrap jquery popper.js

正常にインストールされたかはpackage.jsonで確認できます。

jQueryの導入手順

app/javascript/packs/application.js以下を追記します。

require("jquery")

config/webpack/environment.jsに以下を追記します。

const webpack = require('webpack')

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

Bootstrapの導入手順

app/javascript/src/application.scssを作成し、以下を追記します。

@import '~bootstrap/scss/bootstrap';

app/javascript/packs/application.jsに以下を追記します。

import 'bootstrap'
import '../src/application.scss'

設定ファイルまとめ

app/javascript/packs/application.js
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

import 'bootstrap'
import '../src/application.scss'
app/javascript/src/application.scss
@import '~bootstrap/scss/bootstrap';
config/webpack/evironment.js
const { environment } = require('@rails/webpacker')

const webpack = require('webpack')

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

module.exports = environment
29
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
26