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