繁体   English   中英

在webpacker中使用HTML-javascript的正确方法是什么?

[英]What is the correct way to use in-HTML javascript with webpacker?

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

我已经在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“$ is not defined”错误:

<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>

对代码段的任何建议?

意外修复它:结果是jquery-migrate.min.js导致了以下所有js无法正常工作的问题......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM