【问题标题】:How import own js file into vite?如何将自己的js文件导入到vite中?
【发布时间】:2022-12-09 13:30:40
【问题描述】:

我将 Laravel 与 Vite 一起使用,我想添加带有 Vanilla JS 代码的文件。在我使用 mix 之前,我以前从未使用过 Vite。我尝试将此代码添加到文件 vite.config.js 中,如下例所示:

laravel({
    input: [
        'resources/sass/app.scss',
        'resources/js/app.js',
        'resources/js/test.js', //this is my code
    ],
    refresh: true,
}),

但它不起作用。我需要添加一个库和带有配置的代码。你可以帮帮我吗?

【问题讨论】:

    标签: javascript laravel frontend vite


    【解决方案1】:

    使用 @vite('resources/js/test.js') 指令: https://legacy.laravel-vite.dev/guide/usage.html#vite

        <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
        
            <title>Laravel</title>
            @client
            @vite('main')
            @vite('resources/js/some-script.js')
            <!-- 
            In development:
                <script type="module" src="http://localhost:3000/@vite/client"></script>
                <script type="module" src="http://localhost:3000/resources/scripts/main.ts"></script>
                <script type="module" src="http://localhost:3000/resources/js/some-script.js"></script>
            In production:
                <script type="module" src="http://laravel.local/build/assets/main.66e83946.js"></script>
                <script type="module" src="http://laravel.local/build/assets/some-script.6d3515d2.js"></script>
            -->
        </head>
    

    【讨论】:

      【解决方案2】:

      这个适用于你自己创建的js文件和node模块库js文件

      您需要在vite.config.js 和初始 HTML 文件 (app.blade.php / welcome.blade.php) 中声明它

      在 vite.config.js 中

      export default defineConfig({
          plugins: [
              laravel({
                  input: [
                      'resources/css/app.css',
                      'resources/js/app.js',
                      'resources/js/test.js', //your custom js
                      'node_modules/flowbite/dist/flowbite.js', //node modules js
                      'node_modules/flowbite/dist/datepicker.js'
                  ],
                  refresh: true,
              }),
          ],
      });  
      

      在 HTML.blade.php 中

      <head>
           @vite(['resources/css/app.css', 'resources/js/app.js',         
           'resources/js/test.js',node_modules/flowbite/dist/flowbite.js' 
           ,'node_modules/flowbite/dist/datepicker.js'])
      
      </head>
      

      P.S:我在这里以 Flowbite 插件为例

      【讨论】:

        猜你喜欢
        • 2022-11-14
        • 1970-01-01
        • 2018-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-04
        • 2021-08-25
        • 1970-01-01
        相关资源
        最近更新 更多