$(...).datepicker is not a function in Rails 6

Viewed 3408

Can't understand why I cannot make any jQuery plugin functions (bootstrap, datepicker, etc.) work:

$(...).datepicker() or $(...).modal() respond with ... is not a function in Rails 6

A few notes:

  • $ and jQuery are responding in the console
  • jQuery is included before other scripts
  • jQuery is included once.

application.js:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")
require("parsleyjs")
require("bootstrap-datepicker")

import '../stylesheets/application'
import './bootstrap_custom.js'
import './ru.js'

package.json:

{
  "name": "joy",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0-alpha",
    "@rails/activestorage": "^6.0.0-alpha",
    "@rails/ujs": "^6.0.0-alpha",
    "@rails/webpacker": "^4.0.7",
    "bootstrap": "4.3.1",
    "bootstrap-datepicker": "^1.9.0",
    "jquery": "^3.4.1",
    "parsleyjs": "^2.9.1",
    "popper.js": "^1.16.0",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.8.2"
  }
}

env.js:

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.append(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery',
    Popper: ['popper.js', 'default'],
    Parsley: 'parsleyjs/src/parsley.js',
    datepicker: 'bootstrap-datepicker/js/bootstrap-datepicker.js'
  })
)

module.exports = environment

By the way, if I call bootstrap's modal with data-toggle, it will open successfully.

1 Answers

Try adding following code to application.js:

import jquery from 'jquery';
window.$ = window.jquery = jquery;

And try changing the jquery in application.js like below.

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  'window.jQuery': 'jquery',
  Popper: ['popper.js', 'default'],
  moment: 'moment/moment',
  datepicker: 'bootstrap-datepicker/js/bootstrap-datepicker.js'
}))

module.exports = environment

Related