阿里云主机折上折
  • 微信号
Current Site:Index > Troubleshooting common issues in development environments

Troubleshooting common issues in development environments

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

Environment Variable Configuration Errors

Vite.js uses .env files to manage environment variables. Common issues include variables not loading or being read incorrectly. Check if the .env file is located in the project root directory and if variable names start with VITE_:

# Correct
VITE_API_URL=https://api.example.com

# Incorrect (will not be recognized by Vite)
API_URL=https://api.example.com

Access variables in code via import.meta.env:

console.log(import.meta.env.VITE_API_URL) // Outputs the correct value

If variables are not taking effect, check if vite.config.js overrides the environment variable configuration:

// Incorrect example: overrides the default configuration
export default defineConfig({
  envPrefix: 'APP_' // Requires modifying the variable prefix in .env files as well
})

Port Conflict Issues

When starting the development server, you may encounter the error Port 3000 is already in use. Solutions:

  1. Specify a new port via the command line:
vite --port 4000
  1. Permanently configure it in vite.config.js:
export default defineConfig({
  server: {
    port: 4000,
    strictPort: true // Directly throws an error if the port is occupied instead of trying other ports automatically
  }
})
  1. Find and terminate the process occupying the port (Linux/macOS):
lsof -i :3000
kill -9 <PID>

Hot Module Replacement (HMR) Failure

Hot Module Replacement (HMR) may not work due to the following reasons:

  1. Browser caching issues:
// vite.config.js
export default defineConfig({
  server: {
    hmr: {
      overlay: false // Disable the error overlay to eliminate interference
    }
  }
})
  1. Filesystem watch limitations (common in WSL or virtual machines):
export default defineConfig({
  server: {
    watch: {
      usePolling: true // Enable polling mode
    }
  }
})
  1. Custom middleware interfering with HMR:
// Incorrect example: HMR requests are not handled properly
app.use((req, res, next) => {
  if (req.url.startsWith('/__vite_ping')) {
    return res.status(404).end() // Causes HMR to break
  }
  next()
})

Path Alias Resolution Failure

When configured path aliases like @/* fail to resolve correctly:

  1. Ensure vite.config.js and tsconfig.json are synchronized:
// vite.config.js
import path from 'path'

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  }
})
// tsconfig.json
{
  "compilerOptions": {
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
  1. Additional handling is required for dynamic imports:
// Incorrect example: Directly using aliases will cause build failures
const module = await import('@/components/Button')

// Correct approach: Add ?url suffix
const modulePath = await import('@/components/Button?url')

CSS Preprocessor Issues

Common compilation errors when using Sass/Less:

  1. Preprocessor not installed:
# For Sass
npm install -D sass

# For Less
npm install -D less
  1. Global variables not injected:
// vite.config.js
export default defineConfig({
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`
      }
    }
  }
})
  1. Deprecated deep selector warnings:
/* Compilation warning: >>> is deprecated */
:deep(.child) {
  color: red;
}

/* Correct syntax */
::v-deep(.child) {
  color: red;
}

Dependency Optimization Issues

Common in monorepos or locally linked dependencies:

  1. Forcefully exclude optimization:
// vite.config.js
export default defineConfig({
  optimizeDeps: {
    exclude: ['linked-package'] // Avoid optimizing locally linked packages
  }
})
  1. Include dependencies not automatically discovered:
export default defineConfig({
  optimizeDeps: {
    include: [
      'vue',
      'lodash-es',
      'shared-pkg > nested-module' // Explicitly include deep exports
    ]
  }
})
  1. Resolve CommonJS package issues:
export default defineConfig({
  optimizeDeps: {
    esbuildOptions: {
      supported: {
        'top-level-await': true // Enable top-level await support
      }
    }
  }
})

Build Output Anomalies

Typical issues during production builds:

  1. Incorrect resource paths:
export default defineConfig({
  base: '/project/', // Required when deploying to a subpath
  build: {
    assetsDir: 'static', // Modify the static resource directory
    rollupOptions: {
      output: {
        assetFileNames: 'static/[name]-[hash][extname]' // Customize resource filenames
      }
    }
  }
})
  1. Chunking strategy failure:
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor'
          }
        }
      }
    }
  }
})
  1. Dynamic imports not correctly split:
// Magic comments are required
const module = import(/* webpackChunkName: "chart" */ './Chart.vue')

Browser Compatibility Issues

Handling support for older browsers:

  1. Configure target environment:
// vite.config.js
export default defineConfig({
  build: {
    target: ['es2015', 'edge88', 'firefox78', 'chrome87', 'safari14']
  }
})
  1. Add polyfills:
npm install -D @vitejs/plugin-legacy
import legacy from '@vitejs/plugin-legacy'

export default defineConfig({
  plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    })
  ]
})
  1. Resolve globalThis undefined:
// Add at the top of the entry file
if (typeof globalThis === 'undefined') {
  window.globalThis = window
}

Plugin Conflict Troubleshooting

Debugging methods when multiple Vite plugins interfere with each other:

  1. Disable plugins sequentially:
export default defineConfig({
  plugins: [
    vue(), 
    // Temporarily comment out the following plugins
    // legacy(),
    // visualizer()
  ]
})
  1. Check plugin compatibility:
// Some plugins require specific order
export default defineConfig({
  plugins: [
    checker({
      typescript: true
    }), // Should be placed before the vue plugin
    vue()
  ]
})
  1. Inspect plugin hook execution:
// Custom debugging plugin
const debugPlugin = {
  name: 'debug-hooks',
  config(config) {
    console.log('Config:', config)
    return null
  }
}

Proxy Configuration Issues

Troubleshooting points when the development server proxy is not working:

  1. Rewrite path configuration:
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '') // Remove /api prefix
      }
    }
  }
})
  1. WebSocket proxy:
proxy: {
  '/socket': {
    target: 'ws://localhost:3001',
    ws: true,
    changeOrigin: true
  }
}
  1. Resolve CORS preflight requests:
proxy: {
  '/graphql': {
    target: 'http://localhost:4000',
    changeOrigin: true,
    headers: {
      'Access-Control-Allow-Origin': '*'
    }
  }
}

Type Checking Integration

Handling TypeScript-related issues:

  1. Resolve type extension issues:
// env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_API_URL: string
}
  1. Path alias type support:
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}
  1. Async component types:
// Correct type declaration
const AsyncComp = defineAsyncComponent(
  () => import('./components/AsyncComp.vue')
)

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.