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

如何检测JavaScript应用是否已通过Vite/Rollup进行打包?

如何检测JavaScript应用是否已通过Vite/Rollup打包?

Vite和Rollup本身并没有内置vite.isBuilt()、rollup.hasRolled()这类直接检测打包状态的API,需要通过以下方式实现判断:

  • Vite项目检测方式
    Vite会自动注入环境变量区分开发与生产状态:

    // 生产打包后该值为true,开发模式下为false
    const isBuilt = import.meta.env.PROD;
    

    你也可以在vite.config.js中自定义环境变量,进一步细化状态判断。

  • Rollup项目检测方式
    Rollup需借助插件注入环境变量来区分状态,以@rollup/plugin-replace为例:
    先在Rollup配置中添加插件:

    import replace from '@rollup/plugin-replace';
    
    export default {
      plugins: [
        replace({
          preventAssignment: true,
          'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
        })
      ]
    };
    

    之后在业务代码中判断:

    // 执行生产打包后NODE_ENV会被设置为production
    const isBundled = process.env.NODE_ENV === 'production';
    
  • Electron场景补充
    在Electron应用中,可直接使用内置API检测打包状态:

    const { app } = require('electron');
    const isPackaged = app.isPackaged;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:27:04