ruby-on-rails 未捕获引用错误:$未在Rails 6 jquery webpacker中定义

nxagd54h  于 2023-01-03  发布在  Ruby
关注(0)|答案(2)|浏览(141)

我使用的是Rails 6.0.3.2ruby 2.7.1yarn 1.22.0
我正在尝试做正常的UJS的东西,这是我得到的错误:

VM125:1 Uncaught ReferenceError: $ is not defined
    at <anonymous>:1:1
    at processResponse (rails-ujs.js:283)
    at rails-ujs.js:196
    at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.js:264)

这是我的package.json

{
  "name": "myapp",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/actiontext": "^6.0.2-2",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "bootstrap": "^4.4.1",
    "data-confirm-modal": "^1.6.2",
    "expose-loader": "^1.0.0",
    "flickity": "^2.2.1",
    "jquery": "3.4.1",
    "local-time": "^2.1.0",
    "popper.js": "^1.16.1",
    "stimulus": "^1.1.1",
    "trix": "^1.0.0",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.10.3"
  }
}

这是我的environment.js

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

const webpack = require('webpack')
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Rails: '@rails/ujs'
}))

// environment.loaders.append('jquery', {
//     test: require.resolve('jquery'),
//     use: [{
//         loader: 'expose-loader',
//         options: '$',
//     }, {
//         loader: 'expose-loader',
//         options: 'jQuery',
//     }],
// });

module.exports = environment

正如您从上面注解掉的代码中看到的,我也尝试过对每个this answer使用expose-loader,但这给了我其他错误。
在我的application.js中,我有以下内容:

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

import '../src/jquery.min'
.
.
.
import "controllers"

require("trix")
require("@rails/actiontext")

我该怎么解决这个问题?

olhwl3o2

olhwl3o21#

在中添加以下代码:第一个月

window.jQuery = $;
window.$ = $;

因此可以提取jQuery关键字。

yc0p9oo0

yc0p9oo02#

我有很多问题从webpacker 5迁移到shakapacker.
第一个月
application.js的顶部修复了jQuery问题

相关问题