阿里云主机折上折
  • 微信号
Current Site:Index > Development server options configuration

Development server options configuration

Author:Chuan Chen 阅读数:6899人阅读 分类: 构建工具

Project Configuration and Basic Usage

The Vite.js configuration file vite.config.js is located in the project root directory and customizes the build behavior by exporting a configuration object. The basic configuration structure is as follows:

import { defineConfig } from 'vite'

export default defineConfig({
  // Configuration options
})

Common basic configuration options include:

  • root: Project root directory (default: process.cwd())
  • base: Public base path for development or production environment services
  • publicDir: Folder for static asset serving (default: 'public')
  • cacheDir: Directory to store cache files (default: 'node_modules/.vite')

Example configuration:

export default defineConfig({
  root: './src',
  base: '/admin/',
  publicDir: 'assets',
  cacheDir: '../.vite_cache'
})

Development Server Options Configuration

The development server is configured via the server option, supporting the following common parameters:

Host and Port Settings

server: {
  host: '0.0.0.0',  // Specifies which IP address the server should listen on
  port: 3000,       // Specifies the development server port
  strictPort: true, // Exits directly if the port is occupied
  open: '/login'    // Automatically opens the browser to the specified route on startup
}

Proxy Configuration

Implement API request proxying to resolve cross-origin issues:

server: {
  proxy: {
    '/api': {
      target: 'http://jsonplaceholder.typicode.com',
      changeOrigin: true,
      rewrite: path => path.replace(/^\/api/, ''),
      // More advanced configurations
      configure: (proxy, options) => {
        // Can access the underlying http-proxy instance
      }
    }
  }
}

HTTPS Configuration

Enable HTTPS development server:

server: {
  https: {
    key: fs.readFileSync('path/to/key.pem'),
    cert: fs.readFileSync('path/to/cert.pem')
  }
}

Or use a self-signed certificate:

server: {
  https: true
}

Filesystem Restrictions

Control access to the filesystem:

server: {
  fs: {
    strict: true,      // Restrict to workspace root directory
    allow: [
      '/src/assets',
      '/node_modules/.vite'
    ],
    deny: ['.env', '*.secret']
  }
}

Hot Module Replacement Configuration

HMR-related configuration example:

server: {
  hmr: {
    overlay: false,    // Disable error overlay
    protocol: 'ws',    // Use WebSocket protocol
    host: 'localhost',
    port: 3001,
    // Fully customize HMR connection
    server: {
      // Custom WebSocket server implementation
    }
  }
}

Custom Middleware

Extend development server functionality:

server: {
  middlewareMode: true,
  configureServer(server) {
    server.middlewares.use((req, res, next) => {
      if (req.url === '/custom') {
        res.end('Hello from custom middleware')
      } else {
        next()
      }
    })
  }
}

Pre-Build Options

Optimize dependency pre-building:

optimizeDeps: {
  entries: [
    'src/main.js',
    'src/entries/*.js'
  ],
  exclude: ['heavy-package'],
  include: ['missing-dep'],
  force: true,  // Force re-pre-building
  esbuildOptions: {
    plugins: [
      // Custom esbuild plugins
    ]
  }
}

Environment Variable Configuration

Environment variable handling example:

define: {
  __APP_VERSION__: JSON.stringify('1.0.0'),
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
},
envDir: './env',  // Environment variable file directory
envPrefix: 'VITE_' // Only inject environment variables with the specified prefix

Build Target Configuration

Build targeting different browsers:

build: {
  target: ['es2020', 'edge88', 'firefox78', 'chrome87', 'safari14'],
  polyfillModulePreload: false,
  cssTarget: 'chrome61'  // CSS minification target
}

Advanced Server Configuration

Complete server configuration example:

server: {
  watch: {
    usePolling: true,  // Requires polling for network filesystems
    interval: 1000     // Polling interval
  },
  warmup: {
    clientFiles: [
      './src/utils/*.js',
      './src/components/**/*.vue'
    ]
  },
  chokidar: {
    ignoreInitial: true,
    awaitWriteFinish: {
      stabilityThreshold: 2000,
      pollInterval: 100
    }
  }
}

Multi-Environment Configuration Handling

Loading different configurations based on environments:

// vite.config.js
export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  
  return {
    define: {
      __APP_ENV__: JSON.stringify(env.APP_ENV)
    },
    server: {
      proxy: env.API_PROXY ? {
        '/api': {
          target: env.API_PROXY
        }
      } : undefined
    }
  }
})

Plugin System Integration

Common plugin configuration examples:

import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'

export default defineConfig({
  plugins: [
    vue(),
    legacy({
      targets: ['defaults', 'not IE 11']
    }),
    // Custom plugins
    {
      name: 'custom-plugin',
      config(config) {
        // Modify configuration
      },
      configureServer(server) {
        // Extend server
      }
    }
  ]
})

Performance Optimization Configuration

Build optimization options:

build: {
  minify: 'terser',  // Or 'esbuild'
  terserOptions: {
    compress: {
      drop_console: true
    }
  },
  sourcemap: 'hidden',
  chunkSizeWarningLimit: 1000,
  reportCompressedSize: false,
  rollupOptions: {
    output: {
      manualChunks(id) {
        if (id.includes('node_modules')) {
          return 'vendor'
        }
      }
    }
  }
}

Custom Build Logic

Extend Rollup configuration:

build: {
  rollupOptions: {
    input: {
      main: 'index.html',
      admin: 'admin.html'
    },
    plugins: [
      require('rollup-plugin-image')({
        exclude: /\.svg$/
      })
    ],
    external: ['jquery'],
    output: {
      globals: {
        jquery: '$'
      }
    }
  }
}

Debugging Configuration

Development debugging support:

server: {
  sourcemapIgnoreList(sourcePath) {
    return sourcePath.includes('node_modules')
  },
  debug: {
    inspector: {
      host: '127.0.0.1',
      port: 9229
    }
  }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.