DEV Community

Christian Sedlmair
Christian Sedlmair

Posted on • Edited on

19 2 1 1 1

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

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (5)

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
 
zhai_zhengqing_265bd0873a profile image
Zhai Zhengqing

Thanks, the post helps me a lot. Could you add how to config using cdn to load jquery, thanks in advance.

Collapse
 
nigel447 profile image
nigel447

thanks for sharing this, respect

Collapse
 
chmich profile image
Christian Sedlmair

Thanks nigel447

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay