Vite中获取npm run script的自定义参数

2,865 阅读1分钟

由于笔者其中一个demo项目用到了electron,并写了一个Vite插件使得开发环境下,项目启动时就会运行在electron环境下

image.png

但是笔者希望能通过npm run script的参数去控制项目是否运行在electron环境下,就要用到自定义参数了。

配置自定义参数

自定义参数以 '-- --'传递

// package.json
 "scripts": {
    "dev": "vite --mode development --port 8080",
    "dev:electron": "vite --mode development --port 8080 -- --runtimeEnv electron", // 自定义参数
    "build": "vue-tsc && vite build",
    "preview": "vite preview"
  },

查看参数

在vite.config.ts文件下console.log 打印一下参数

export default defineConfig(() => {
    console.log(process.argv);
});

运行npm run dev:electron

image.png

Vite中配置plugins

export default defineConfig(() => {
    const isElectron = process.argv.includes("electron"); // 查看参数是否有electron
    const plugins = [
        vue(),
        viteElectronProd(),
    ];

    if (isElectron) {
        plugins.push(viteElectronDev());
    }

    return {
        base: "./",
        plugins,
    };
});

最终效果

image.png