6

I am trying to use jQuery with laravel 9 + vite. It is working fine in dev but while built, i am getting jQuery is not a function

libs.ts

import * as jQuery from 'jquery';
declare global {
    interface Window {
        jQuery: typeof jQuery;
        $: typeof jQuery;
    }
}

window.$ = window.jQuery = jQuery;

main.ts

jQuery(function(){
     console.log(jQuery(".datepicker"));
});

vite.config.ts

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import { esbuildCommonjs } from '@originjs/vite-plugin-commonjs'

export default defineConfig({
  plugins: [
    laravel({
      input: [
        'resources/scss/libs.scss',
        'resources/scss/main.scss',
        'resources/css/app.css',
        'resources/js/libs.ts',
        'resources/js/main.ts',
      ],
      refresh: true,
    }),
  ],
  optimizeDeps: {
    include: ['jquery/dist/jquery'],
    esbuildOptions: {
      plugins: [
        esbuildCommonjs(['jquery/dist/jquery'])
      ]
    }
  },
  build: {
    rollupOptions: {
      plugins: [
        {
          name: 'no-tree',
          transform(_, id) {
            if (id.includes('jquery/dist/jquery')) {
              return { moduleSideEffects: 'no-tree' }
            }
          }
        }
      ],
      output: {
        globals: {
          jquery: 'window.jQuery',
        }
      }
    }
  }
});

Output of npm run dev

Output of npm run dev

Output of npm run build

Output of npm run build

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Alaksandar Jesus Gene
  • 6,523
  • 12
  • 52
  • 83

1 Answers1

4

Inject jQuery using @rollup/plugin-inject:

vite.config.ts

import { defineConfig } from 'vite';
import inject from '@rollup/plugin-inject';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    inject({
        //Remember to add `"jquery": "^3.6.1"` in `dependencies` for `package.json`
        jQuery: "jquery",
        "window.jQuery": "jquery",
        $: "jquery"
    })
  ]
})
Mithsew
  • 1,129
  • 8
  • 20
Nhok V
  • 566
  • 3
  • 11