You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite未打包仅在Blade组件中引用的脚本,如何强制构建?

问题解决:Vite生产构建生成空JS文件的处理方法

问题根源

生产构建时Vite依赖的Rollup会执行tree-shaking优化,把它判定为「未被实际使用」的模块内容移除。你的mycomponent.js仅导出类但无执行代码,且Blade中用Vite::asset动态导入的方式无法被Vite的静态分析检测到;再加上vite.config.js里通过globSync把所有JS文件设为入口,Rollup会认为这个入口模块没有实际用途,最终生成空文件。


方案一:修正Blade导入方式(推荐)

去掉单独的@vite指令和Vite::asset动态导入,改用Vite能静态分析的模块导入逻辑:

  1. 先在vite.config.js中添加别名(简化导入路径):
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import { resolve } from 'path';

export default defineConfig(({command, mode}) => {
    return {
        resolve: {
            alias: {
                '@': resolve(__dirname, 'resources/js'), // 用@指代resources/js目录
            },
        },
        appType: "mpa",
        plugins: [
            laravel({
                input: ["resources/sass/app.scss"], // 只保留核心入口,让Vite自动追踪依赖
                refresh: true,
            }),
        ],
        build: {
            rollupOptions: {output: {}},
            chunkSizeWarningLimit: 800,
        },
    }
});
  1. 修改Blade组件的脚本部分:
<div id="{{ $id }}" class="mycomponent-container"></div>

<script type="module">
    // 用别名直接导入模块,Vite会自动处理依赖打包
    import MyComponent from '@/mycomponent.js';

    let containerId = @json($id);
    new MyComponent(document.getElementById(containerId));
</script>

这样Vite构建时能直接检测到导入关系,将mycomponent.js作为依赖正常打包。


方案二:给模块添加副作用标记

如果不想修改导入方式,可在mycomponent.js顶部添加注释,告诉Rollup该模块存在副作用,不能被tree-shaking移除:

/* side-effects */
"use strict";

class MyComponent {
    constructor(container) {
        container.innerHTML = "<b>foo</b>";
    }
}

export default MyComponent;

方案三:配置Rollup保留入口签名

若需要保留globSync的入口配置,可在vite.config.js的Rollup选项中强制保留入口文件内容:

import laravel from 'laravel-vite-plugin';
import { globSync } from "glob";
import { defineConfig } from 'vite';

export default defineConfig(({command, mode}) => {
    return {
        appType: "mpa",
        plugins: [
            laravel({
                input: globSync(["resources/js/**/*.*", "resources/sass/app.scss"]),
                refresh: true,
            }),
        ],
        build: {
            rollupOptions: {
                output: {},
                preserveEntrySignatures: 'allow-extension', // 强制保留入口文件内容
            },
            chunkSizeWarningLimit: 800,
        },
    }
});

内容的提问来源于stack exchange,提问作者miken32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 20:42:12