在生产模式下运行vite时,“jQuery不是函数”

jutyujz0  于 2023-01-25  发布在  jQuery
关注(0)|答案(1)|浏览(316)

我正在尝试使用jQuery和laravel 9 + vite。它在开发中运行良好,但在构建时,我发现jQuery不是一个函数

    • 资料库. ts**
import * as jQuery from 'jquery';
declare global {
    interface Window {
        jQuery: typeof jQuery;
        $: typeof jQuery;
    }
}

window.$ = window.jQuery = jQuery;
    • 主文件. ts**
jQuery(function(){
     console.log(jQuery(".datepicker"));
});
    • 维生素配置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',
        }
      }
    }
  }
});
    • npm运行开发的输出**

    • npm运行构建的输出**

jhdbpxl9

jhdbpxl91#

使用@rollup/plugin-inject注入jQuery:

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"
    })
  ]
})

相关问题