DEV Community

Christian Sedlmair
Christian Sedlmair

Posted on • Updated on

Setup jQuery on Vite

Overview

Prerequisites

Vite

Setup

$ npm i @rollup/plugin-inject --save-dev
$ npm i jquery
Enter fullscreen mode Exit fullscreen mode

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(),
    ],
  })
Enter fullscreen mode Exit fullscreen mode

Restart the Server

frontend/entrypoints/application.js

import $ from 'jquery';
window.$ = $;
Enter fullscreen mode Exit fullscreen mode

Refresh the browser

Testcode

frontend/entrypoints/application.js

window.test_jquery = function() {
    $('#test-jquery').html('jQuery works!')
}
Enter fullscreen mode Exit fullscreen mode

app/views/layout/application.haml

%button#test-jquery{onclick: 'test_jquery()'}
  Test if jQuery is working
Enter fullscreen mode Exit fullscreen mode

=> Click the Button and you should see: «jQuery works!»

Overview

Top comments (4)

Collapse
 
rohimchou profile image
RohimChou

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 packaging

Collapse
 
chmich profile image
Christian Sedlmair

Thanks, RohimChou, i corrected it.

Collapse
 
nigel447 profile image
nigel447

thanks for sharing this, respect

Collapse
 
chmich profile image
Christian Sedlmair

Thanks nigel447