代码之家  ›  专栏  ›  技术社区  ›  Chris L

使用Vite在单页上导入jQuery

  •  0
  • Chris L  · 技术社区  · 10 月前

    我正在用Vite开发Laravel 11项目。在我的一个管理页面上,我需要jQuery来显示编辑器。 我制作了一个js文件供编辑器加载:

    import "trumbowyg/dist/ui/trumbowyg.min.css";
    import "trumbowyg";
    
    $(document).ready(function () {
        $.trumbowyg.svgPath = window.trumbowygSvgPath;
        $("#trumbowyg-editor").trumbowyg();
    });
    

    这是在我的bladefile中打开的:

            <script type="module">
                    window.trumbowygSvgPath = '{{ Vite::asset('resources/images/icons.svg') }}';
            </script>
            <script type="module" src="{{ mix('resources/js/trumbowyg-page.js') }}"></script>
    

    这仅在我在bootstrap.js中导入jQuery时有效。

    是否有可能只为单个站点而不是全局导入jQuery?

    1 回复  |  直到 10 月前
        1
  •  1
  •   Alex    10 月前

    你能做的就是使用安装jQuery npm install jquery 。在资源文件夹中,您可以创建一个JavaScript文件,在其中导入jQuery。

    那么你应该更新你的 vite.config.js file,将JavaScript文件添加到配置的输入中。如果您已将文件添加到列表中,则可以使用 @vite('resources/js/file-specific.js') 。现在,您只在该特定页面上包含了jQuery。

    resources/js/page-specific.js

    import $ from 'jquery';
    
    // Example usage of jQuery
    $(document).ready(function () {
        console.log('jQuery is loaded and ready on this page!');
    });
    

    Vite配置

    import { defineConfig } from 'vite';
    import laravel from 'laravel-vite-plugin';
    
    export default defineConfig({
        plugins: [
            laravel({
                input: [
                    'resources/js/app.js',
                    'resources/js/page-specific.js', // your page-specific entry point
                ],
                refresh: true,
            }),
        ],
    });
    

    您的刀片文件:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <!-- Your head content -->
        @vite('resources/js/page-specific.js') <!-- Include the specific JS file -->
    </head>
    <body>
        <!-- Your body content -->
    
        <h1>This page has jQuery loaded!</h1>
    </body>
    </html>