首页 > 解决方案 > Can't find application.js with javascript_pack_tag(Webpacker)

问题描述

I have installed Webpacker gem in my Rails app and don't really know how to include app.js file into app/javascript/packs folder.

I put

<%= javascript_pack_tag 'application' %>

into my application.html.erb layout and

//= require jquery/dist/jquery
//= require jquery-ui/ui/jquery-ui
//= require jquery-ujs

into it.

After all in some view(ex. index.html.erb) I have some jQuery in script tag:

<script>

  jQuery(document).ready(function(){...

And when I refresh page and look in console I get:

GET http://localhost:3000/packs/application-5e96d8f9533313f79af6.js net::ERR_ABORTED 500 (Internal Server Error)

and

Uncaught ReferenceError: jQuery is not defined

The question is why javascript_pack_tag transforms application.js into application-5e96d8f9533313f79af6.js(with these numbers) in HTML and from where is that coming?

Also I'm mentioning that I'm transforming my app from Bower to Webpack(within Webpacker gem) and not really sure how to include my Bower components to be used with Webpacker.

Any reference would be appreciated

标签: javascriptruby-on-railswebpack

解决方案


包名称中的这些数字是正常的,它是文件摘要,sprockets 在生产中也这样做(它用于缓存清除并确保客户端上的代码正确)。

//= require指令用于链轮(又名资产管道),在 webpacker 中您应该使用 javascript 导入(或webpack.ProvidePlugin在配置中使用,以便jQuery在使用时自动加载标识符)。

您还必须切换到 npm 依赖项 -yarn add jquery jquery-ui jquery-ujs

plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery'",
        "window.$": "jquery"
    })
  ]

并使用单独的导入(在每个文件中导入那里使用的内容,就像没有其他文件一样,webpack 将处理重复项):

import $ from 'jquery';
import 'jquery-ui/themes/base/core.css';
import 'jquery-ui/themes/base/theme.css';
import 'jquery-ui/themes/base/selectable.css';
import 'jquery-ui/ui/core';
import 'jquery-ui/ui/widgets/selectable'; // and so on
import {} from 'jquery-ujs'

推荐阅读