【问题标题】:Vite JS + Laravel jQuery working on dev not on prodVite JS + Laravel jQuery 在开发而不是产品上工作
【发布时间】:2023-01-18 13:17:54
【问题描述】:

我正在尝试将 jQuery 与 laravel 9 + vite 一起使用。它在开发中运行良好,但在构建时,我得到 jQuery is not a function

库文件

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

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',
        }
      }
    }
  }
});

npm run dev 的输出

npm run build 的输出

【问题讨论】:

  • 任何更新?与 laravel 9 + Vite + inertia 有同样的问题

标签: vite laravel-9


【解决方案1】:

像这样注入 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"
    })
  ]
})

【讨论】:

    猜你喜欢
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多