1
1

More than 1 year has passed since last update.

【Rails】Rails6でのjQueryを使うときのwebpackerの設定

Posted at

初めに

Rails6でのwebpacker の設定が分からなくなっていたのでここで書き残しておきます。

環境

  • Rails 6.1.4
  • Ruby 2.7.4
  • webpacker 5.4.3

webpacker

Rails6 の javascript の設定は config/webpacke の下にあるファイルで行います。
今回は jquery が使えるようにします。

enviroment.js

config/webpack/environment.js
const { environment } = require("@rails/webpacker");

const webpack = require("webpack");

environment.plugins.prepend(
  "Provide",
  new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    jquery: "jquery",
    Popper: ["popper.js", "default"],
  })
);
module.exports = environment;

application.js

javasccript/packs/application.js

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

import $ from "jquery/dist/jquery.js

globalThis.jQuery = $;
globalThis.$ = $;

これで jquery がエラーなく動きます。

参考

Issue loading jQuery in Webpacker 5- stackoverflow

1
1
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
1
1