在Webpacker中使用HTML内javascript的正确方法是什么?

时间:2019-04-20 10:26:49

标签: jquery ruby-on-rails webpacker

我正在使用webpacker设置一个新的Rails 5.2项目,尝试实现静态的Boostrap模板。但是,我不确定将Boostrap模板中的HTML内JavaScript包含在rails / webpacker中的最佳方法是什么。

我已经在application.js中包含了jQuery,但是控制台一直在说$未定义。

这是我的app / javascript / packs / javascript.js:

/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb


// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
const images = require.context('../images', true)
const imagePath = (name) => images(name, true)

console.log('Hello World from starter')

import '../css/theme.css'

//
// front basic
//

// <!-- JS Global Compulsory -->
import "jquery/dist/jquery.min.js"
import "jquery-migrate/dist/jquery-migrate.min.js"
import "bootstrap/dist/js/bootstrap.min.js"
import "popper.js/dist/umd/popper.min.js"

在我的environment.js中,我有:

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

const webpack = require('webpack')

// Add an additional plugin of your choosing : ProvidePlugin
environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
    $: 'jquery',
    JQuery: 'jquery',
    jquery: 'jquery',
    jQuery: 'jquery',
    'window.Tether': "tether",
    Popper: ['popper.js', 'default'], // for Bootstrap 4
  })
)

module.exports = environment

在这里出现“未定义$”的index.html.erb错误:

<h1>Templates#starter</h1>
<p>Find me in app/views/templates/starter.html.erb</p>


<script type="text/javascript">
    $(window).on('load', function () { // not working
        // some more code
        console.log("????");
    });
</script>

对摘要有何建议?

1 个答案:

答案 0 :(得分:0)

意外修复:事实证明jquery-migrate.min.js导致以下所有js无法正常工作的问题...