How to Change vite application port
Asked Answered
O

4

44

If you are change the vite application port please follow the procedure.

"scripts": {
  "dev": "vite --port 3006",
  "build": "vite build",
  "preview": "vite preview"
}
Osteogenesis answered 6/4, 2022 at 8:2 Comment(1)
Is this an answer or a question?Clea
L
78

Try add your port into vite.config.ts:

 export default defineConfig({
  // ...some configs
  server: {
    port: 3006,
  },
});
Lifesaving answered 2/8, 2022 at 20:16 Comment(3)
I created the file but is not workingCup
@Cup make sure to run just vite and not vite preview. vite preview does not look at that setting.Francie
@Cup just to clarify, vite preview looks at preview, which is the identical config format to serverAlcoholize
I
13

you can modify the dev script in the package.json file and set the --port to the one you want .

Ingathering answered 22/8, 2022 at 23:36 Comment(0)
G
11

in vite.config.ts you can manage the port separately for production and development. PORT server: production. PORT preview: development

export default defineConfig({
//change port for production
  preview: {
    port: 3001,
  },
// for dev
  server: {
    port: 3000,
  },
});
Gabbert answered 16/12, 2023 at 20:5 Comment(1)
Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?Scrip
A
2

In addition to defining it in the config or providing it on the command line, it's also possible to configure the port in .env files - anything in .env / .env.production etc that's prefixed with VITE_ will be automatically available to your app via import.meta.env and can be loaded into the vite.config.ts file using loadEnv:

import react from '@vitejs/plugin-react';
import { ConfigEnv, defineConfig, loadEnv } from 'vite';

export default defineConfig(({command, mode} : ConfigEnv) => {
    console.log(`configuring vite with command: ${command}, mode: ${mode}`);
    // suppress eslint warning that process isn't defined (it is)
    // eslint-disable-next-line
    const cwd = process.cwd();
    console.log(`loading envs from ${cwd} ...`);
    const env = {...loadEnv(mode, cwd, 'VITE_')};
    console.log(`loaded env: ${JSON.stringify(env)}`);

    // reusable config for both server and preview
    const serverConfig = {
        host: true,
        port: Number(env.VITE_PORT),
        strictPort: true,
    };

    return {
        base: '/',
        plugins: [react()],
        preview: serverConfig,
        server: serverConfig,
    };
});

Alcoholize answered 28/1 at 11:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.