阿里云主机折上折
  • 微信号
Current Site:Index > File system exclusion rules

File system exclusion rules

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

Project Configuration and Basic Usage: File System Exclusion Rules

Vite.js allows excluding specific files or directories through configuration to prevent them from being processed or included in the build output. File system exclusion rules are useful for optimizing build performance, avoiding exposure of sensitive files, or skipping unnecessary processing.

Basic Methods for Configuring Exclusion Rules

In vite.config.js, you can control file system access permissions using the server.fs.deny or server.fs.allow options. These options accept an array that can include strings, regular expressions, or functions.

import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    fs: {
      // Deny access to the following files
      deny: ['.env', '.git'],
      // Only allow access to the following directories
      allow: ['src', 'public']
    }
  }
})

Using String Pattern Matching

The simplest way to exclude files is by using string paths. Vite will match these paths against the requested URLs.

export default defineConfig({
  server: {
    fs: {
      deny: [
        'node_modules',  // Exclude the entire node_modules directory
        '*.log',        // Exclude all log files
        'secret/*.txt' // Exclude .txt files in the secret directory
      ]
    }
  }
})

Using Regular Expressions for Matching

For more complex matching requirements, you can use regular expressions:

export default defineConfig({
  server: {
    fs: {
      deny: [
        /\.tmp$/,       // Exclude all .tmp files
        /\/private\//,  // Exclude files containing /private/ in their path
        /^\/config\//   // Exclude paths starting with /config/
      ]
    }
  }
})

Using Functions for Custom Exclusion

When complex logic is needed for exclusion, you can use functions:

export default defineConfig({
  server: {
    fs: {
      deny: [
        (path) => {
          // Exclude files larger than 1MB
          const stats = fs.statSync(path)
          return stats.size > 1024 * 1024
        },
        (path) => {
          // Exclude files created by a specific user
          const stats = fs.statSync(path)
          return stats.uid === 1000
        }
      ]
    }
  }
})

Practical Use Cases for Exclusion Rules

  1. Protecting Sensitive Files: Prevent accidental access to .env or configuration files.
  2. Improving Development Server Performance: Skip processing large binary files or generated files.
  3. Avoiding Cache Pollution: Exclude temporary files or log files.
  4. Security Hardening: Prevent access to system directories or hidden files.
// Example of a typical security configuration
export default defineConfig({
  server: {
    fs: {
      deny: [
        '.env',
        '.env.*',
        '*.pem',
        '/etc/*',
        '/root/*',
        '/tmp/*',
        '/var/*',
        'node_modules/.cache/*'
      ],
      allow: [
        process.cwd() // Only allow access to the project root directory
      ]
    }
  }
})

Relationship Between Exclusion Rules and Builds

Note that file system exclusion rules primarily affect the development server. To exclude files in production builds, you need to use Rollup's configuration:

export default defineConfig({
  build: {
    rollupOptions: {
      external: [
        /^node:.*/, // Exclude all node: protocol imports
        'fs',
        'path'
      ]
    }
  }
})

Common Issues and Solutions

  1. Exclusion Rules Not Working:

    • Check if the paths are correct.
    • Ensure no other configurations are overriding the exclusion rules.
    • Try using absolute paths.
  2. Need to Dynamically Exclude Files:

    export default defineConfig(({ command }) => ({
      server: {
        fs: {
          deny: command === 'serve' ? ['.env.local'] : []
        }
      }
    }))
    
  3. Exclusion Rules Are Too Strict Causing Functionality Issues:

    • Gradually add exclusion rules and test their impact.
    • Use server.fs.strict to control strict mode.
    export default defineConfig({
      server: {
        fs: {
          strict: false // Allow access to files outside the project root
        }
      }
    })
    

Advanced Exclusion Techniques

Combine multiple conditions for complex exclusions:

export default defineConfig({
  server: {
    fs: {
      deny: [
        (path) => {
          const isLarge = fs.statSync(path).size > 500000
          const isMedia = /\.(mp4|mov|avi)$/.test(path)
          return isLarge && isMedia
        }
      ]
    }
  }
})

Use environment variables to control exclusion rules:

export default defineConfig({
  server: {
    fs: {
      deny: [
        process.env.NODE_ENV === 'production' ? '.env.development' : ''
      ].filter(Boolean)
    }
  }
})

Interaction Between Exclusion Rules and the Plugin System

Some plugins may bypass Vite's file system restrictions. In such cases, you need to configure them separately:

import somePlugin from 'vite-plugin-some'

export default defineConfig({
  plugins: [
    somePlugin({
      exclude: ['**/test/**', '**/fixtures/**']
    })
  ]
})

Performance Considerations

Excessive use of exclusion rules may impact build performance, especially when using functions for complex matching. Recommendations:

  1. Prefer simple string or regex matching.
  2. Avoid synchronous I/O operations in exclusion functions.
  3. Use caching for frequently accessed paths.
const exclusionCache = new Map()

export default defineConfig({
  server: {
    fs: {
      deny: [
        (path) => {
          if (exclusionCache.has(path)) {
            return exclusionCache.get(path)
          }
          const result = complexCheck(path)
          exclusionCache.set(path, result)
          return result
        }
      ]
    }
  }
})

File System Exclusion and Module Resolution

Exclusion rules affect module resolution behavior. If you need to exclude certain modules but retain their type definitions:

export default defineConfig({
  server: {
    fs: {
      deny: ['**/*.js'],
      allow: ['**/*.d.ts']
    }
  }
})

Debugging Exclusion Rules

You can view exclusion rule matches by setting server.debug:

export default defineConfig({
  server: {
    debug: {
      fs: {
        showExcluded: true
      }
    }
  }
})

This will log excluded file access attempts to the console, helping debug configuration issues.

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

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