通过Webpack在Rails中安装jQuery时未定义$ [英] $ is not defined when installing jQuery in Rails via Webpack

查看:181
本文介绍了通过Webpack在Rails中安装jQuery时未定义$的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Webpack在Rails 6.0.0.rc1中安装jQuery,但我不确定丢失了什么,但是尽管能够编译jQuery,但在浏览器控制台中却出现错误$ is not defined .

I'm trying to install jQuery in Rails 6.0.0.rc1 via Webpack and I'm not sure what I'm missing but I'm getting the error $ is not defined in the browser console despite being able to compile jQuery.

我用yarn add jquery添加了jQuery,所以我的package.json看起来像这样

I've added jQuery with yarn add jquery, so my package.json looks like this

{
  "name": "muladeseis_app",
  "private": true,
  "dependencies": {
    "@babel/preset-react": "^7.0.0",
    "@rails/actioncable": "^6.0.0-alpha",
    "@rails/activestorage": "^6.0.0-alpha",
    "@rails/ujs": "^6.0.0-alpha",
    "@rails/webpacker": "^4.0.2",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
    "jquery": "^3.4.0",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.3.1"
  }
} 

我的app/javascript/packs/application.js需要从node_modules进行jquery

My app/javascript/packs/application.js is requiring jquery from node_modules

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

我尝试通过以下操作在config/webpack/environment.js中注册$:

And I've tried to register $ in config/webpack/environment.js by doing:

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

const webpack = require('webpack')

module.exports = environment

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

每当我在视图中添加带有$引用的脚本时,都会得到Uncaught ReferenceError: $ is not defined.

Whenever I add a script in my views with a $ reference I get Uncaught ReferenceError: $ is not defined.

我已经检查了StackOverflow答案,例如,以查看如果我不正确地注册了关键字符'$',但是我只找到建议使用ProvidePlugin的答案,该答案已经在我的配置中引用了.

I've checked in StackOverflow answers like this to see if I'm registering incorrectly the key character '$' but I've found only answers suggesting using the ProvidePlugin which I'm already referring to in my configuration.

如果我在浏览器检查器中浏览我的应用程序源,我确实会看到jQuery代码集成在localhost:3000 >> packs/js中,因此问题不是Webpack找不到jQuery,而是关键字"$"和无法识别jQuery.

Also if I explore my app Sources in the browser inspector I do see jQuery code integrated in localhost:3000 >> packs/js so the issue is not that Webpack is not finding jQuery but that the key words '$' and 'jQuery' are not recognised.

感谢您的调试帮助.

推荐答案

我缺少了什么.

app/javascript/packs/application.js中忘记声明:

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

因此可以选择jQuery关键字.

So jQuery keywords could be picked up.

这篇关于通过Webpack在Rails中安装jQuery时未定义$的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆