$(...).tooltip 不是函数 rails 6 webpack

$(...).tooltip is not a function rails 6 webpack

我试过更改 bootstrap、jquery 和 popper 的版本,但没有成功。我不认为我使用了 jquery 的一个以上版本。不知道哪里出了问题。如果有人帮助我找到我丢失的东西,那就太好了。

这是我的文件列表,

package.json:

{
  "name": "kf",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-free": "^5.12.1",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "bootstrap": "^4.4.1",
    "jquery": "^3.4.1",
    "popper.js": "^1.16.1",
    "sweetalert2": "^9.8.2"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.10.3"
  }
}

config/webpack/environment.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']
  })
);

module.exports = environment;

application.js

require('@rails/ujs').start();
require('jquery/dist/jquery');
require('popper.js/dist/umd/popper');
require('bootstrap/dist/js/bootstrap');
require('@fortawesome/fontawesome-free');
require('./owl.carousel.min');
require('./fastclick');
require('./custom-script');
require('./return-to-top');

const Swal = require('sweetalert2');
window.Swal = Swal;
const images = require.context('../images', true);
const imagePath = name => images(name, true);
import 'stylesheets/application';

jQuery(document).ready(function($) {
  $('[data-toggle="tooltip"]').tooltip();
});

警告:

jQuery.Deferred exception: $(...).tooltip is not a function TypeError: $(...).tooltip is not a function

错误:

Uncaught TypeError: $(...).tooltip is not a function

我觉得你的webpack配置应该是这样的

    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        Popper: ['popper.js', 'default']
    }),

如果您仍然有任何错误,请告诉我

我已经通过在 webpack 文件夹中添加一个 custom.js 来解决,就像在 webpack 配置 git 文档中一样:

https://github.com/rails/webpacker/blob/master/docs/webpack.md#configuration

#config/webpack/custom.js

module.exports = {
  resolve: {
    alias: {
      jquery: 'jquery/src/jquery'
    }
  }
};

而我的config/webpack/environment.js改为

const { environment } = require('@rails/webpacker');
const customConfig = require('./custom');
const webpack = require('webpack');

environment.plugins.append(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery',
    Popper: ['popper.js', 'default']
  })
);
environment.config.merge(customConfig);

module.exports = environment;

重新启动服务器,工具提示工作正常。

注意:application.js

中不需要添加require('jquery')require('popper')

根本问题是 tooltip() 并非 一直存在于 jQuery UI 中。它是在 1.9 版本中添加的。证明:

version added: 1.9 (Source: API.jQueryUI.com: Tooltip Widget.)

如果您没有 jQuery UI 1.9 或更高版本,您将收到错误消息:tooltip() is not a function().

不要忘记,通过升级您的 jQuery/jQuery UI 版本,您可能还会引入其他错误,例如 “Uncaught TypeError: a.indexOf is not a function”,但只需搜索即可轻松修复这些错误每个的解决方案并修复它们。这是升级您使用的任何软件包的一般过程,有时会出现问题,但它们总是可以修复的。使用最新的代码是您包管理的最佳盟友。