Prerequisites
Setup
$ npm i @rollup/plugin-inject --save-dev
$ npm i jquery
vite.config.js
add the lines with the «+».
import { defineConfig } from 'vite'
import RubyPlugin from 'vite-plugin-ruby'
+ import inject from "@rollup/plugin-inject";
export default defineConfig({
plugins: [
+ inject({ // => that should be first under plugins array
+ $: 'jquery',
+ jQuery: 'jquery',
+ }),
RubyPlugin(),
],
})
Restart the Server
frontend/entrypoints/application.js
import $ from 'jquery';
window.$ = $;
Refresh the browser
Testcode
frontend/entrypoints/application.js
window.test_jquery = function() {
$('#test-jquery').html('jQuery works!')
}
app/views/layout/application.haml
%button#test-jquery{onclick: 'test_jquery()'}
Test if jQuery is working
=> Click the Button and you should see: «jQuery works!»
Top comments (4)
would be better to use
--save-dev
flag e.g.npm install @rollup/plugin-inject --save-dev
, since the application can run without this plugin after packagingThanks, RohimChou, i corrected it.
thanks for sharing this, respect
Thanks nigel447