Skip to main content

A Reflex Plugin that allows you to fully customize your Vite config

Project description

Reflex Vite Config Plugin

PyPI Version Python Versions License

A Reflex rx.Config() plugin that allows you to fully customize your Vite configuration using Python dictionaries. This plugin seamlessly integrates with Reflex's build system to provide complete control over Vite's build process, development server, and optimization settings.

Table of Contents:

Features

  • Pythonic Configuration: Define Vite configs using Python dictionaries with full type safety
  • Complete Vite API Coverage: Support for all Vite configuration options
  • Raw JavaScript Support: Embed raw JavaScript code where needed using the RawJS wrapper
  • Reflex Default Merging: Utilizes deep merging with Reflex's defaults
  • Type Safety: Type hints for all configuration options
  • Development Tools: Enhanced development server configuration

Requirements

  • Python 3.11+
  • Reflex >= 0.8.17

Quick Start

Installation

pip install reflex-vite-config-plugin

Basic Usage

import reflex as rx
from vite_config_plugin import ViteConfigPlugin

config = rx.Config(
    plugins=[
        ViteConfigPlugin({
            "server": {
                "port": 4000,
                "host": "0.0.0.0"
            },
            "build": {
                "sourcemap": True,
                "target": "es2020"
            }
        })
    ]
)

Advanced Configuration

from vite_config_plugin import ViteConfigPlugin, RawJS

config = rx.Config(
    plugins=[
        ViteConfigPlugin({
            "plugins": [
                RawJS("vue()"),
                RawJS("typescript()"),
            ],
            "server": {
                "port": 3000,
                "hmr": {
                    "port": 24678,
                    "overlay": True
                },
                "proxy": {
                    "/api": "http://localhost:8000"
                }
            },
            "build": {
                "target": "es2020",
                "sourcemap": True,
                "rollupOptions": {
                    "external": ["react", "react-dom"],
                    "output": {
                        "manualChunks": RawJS("""
                            (id) => {
                                if (id.includes('node_modules')) {
                                    return 'vendor';
                                }
                            }
                        """)
                    }
                }
            },
            "resolve": {
                "alias": [
                    {"find": "@", "replacement": "./src"},
                    {"find": "@components", "replacement": "./src/components"},
                    {"find": "@utils", "replacement": "./src/utils"}
                ]
            },
            "optimizeDeps": {
                "include": ["lodash", "axios"],
                "exclude": ["@my/custom-package"]
            }
        },
        imports=[
            'import vue from "@vitejs/plugin-vue";',
            'import typescript from "@rollup/plugin-typescript";'
        ])
    ]
)

Configuration Options

The plugin supports all Vite configuration options through typed dictionaries:

Server Configuration

{
    "server": {
        "host": "localhost",          # Server host
        "port": 3000,                 # Server port
        "strictPort": False,          # Strict port binding
        "https": {                    # HTTPS configuration
            "key": "/path/to/key.pem",
            "cert": "/path/to/cert.pem"
        },
        "proxy": {                    # Proxy configuration
            "/api": "http://localhost:8000",
            "/ws": {
                "target": "ws://localhost:8080",
                "ws": True
            }
        },
        "hmr": {                      # Hot Module Replacement
            "port": 24678,
            "overlay": True
        }
    }
}

Build Configuration

{
    "build": {
        "target": "es2020",           # Build target
        "outDir": "dist",             # Output directory
        "sourcemap": True,            # Generate sourcemaps
        "minify": "esbuild",          # Minification method
        "rollupOptions": {            # Rollup-specific options
            "external": ["react"],
            "output": {
                "format": "es"
            }
        },
        "lib": {                      # Library mode
            "entry": "./src/lib.ts",
            "name": "MyLib",
            "formats": ["es", "umd"]
        }
    }
}

Module Resolution

{
    "resolve": {
        "alias": [                    # Path aliases
            {"find": "@", "replacement": "./src"},
            {"find": "~", "replacement": "./"}
        ],
        "extensions": [".js", ".ts", ".jsx", ".tsx"],
        "mainFields": ["browser", "module", "main"]
    }
}

CSS Configuration

{
    "css": {
        "postcss": "./postcss.config.js",
        "preprocessorOptions": {
            "scss": {
                "additionalData": "$primary: #1976d2;"
            },
            "less": {
                "math": "parens-division"
            }
        }
    }
}

Using RawJS for JavaScript Code

For configuration values that need to be raw JavaScript, use the RawJS wrapper:

from vite_config_plugin import RawJS

vite_config = {
    "define": {
        "__VERSION__": RawJS("JSON.stringify(process.env.npm_package_version)"),
        "__DEV__": RawJS("process.env.NODE_ENV === 'development'")
    },
    "plugins": [
        RawJS("react()"),
        RawJS("viteTsconfigPaths()")
    ],
    "build": {
        "rollupOptions": {
            "output": {
                "manualChunks": RawJS("""
                    (id) => {
                        if (id.includes('node_modules')) {
                            if (id.includes('react')) {
                                return 'react-vendor';
                            }
                            return 'vendor';
                        }
                    }
                """)
            }
        }
    }
}

Custom Imports

Add custom JavaScript imports to your Vite config:

config = rx.Config(
    plugins=[
        ViteConfigPlugin(
            config,
            imports=[
                'import react from "@vitejs/plugin-react";',
                'import { resolve } from "path";',
                'import { defineConfig, loadEnv } from "vite";'
            ]
        )
    ]
)

Custom Functions

Add custom JavaScript functions to your Vite config:

func = """
function foo() {
    return 'bar';
}
"""
config = rx.Config(
    plugins=[
        ViteConfigPlugin(
            config,
            functions=[RawJS(func)]
        )
    ]
)

API Reference

ViteConfigPlugin

The main plugin class for Vite configuration.

ViteConfigPlugin(
    config: ViteConfig,
    *,
    imports: list[str] | None = None,
    functions: list[RawJS] | None = None,
    dependencies: list[str] | None = None,
    extra_configs: list[ViteConfig] | None = None,
)

Parameters:

  • config: A dictionary containing Vite configuration options.
  • imports: Optional list of JavaScript import statements.
  • functions: Optional list of RawJS objects containing Javascript functions used in the Vite config.
  • dependencies: Optional list of frontend dependencies to install.
  • extra_configs: Optional list of ViteConfig dicts to merge.

RawJS

Wrapper for embedding raw JavaScript code in configuration.

RawJS(code: str)

Parameters:

  • code: Raw JavaScript code string

Type Definitions

The plugin includes comprehensive TypeScript-style type definitions:

  • ViteConfig: Main configuration type
  • Server: Development server options
  • BuildOptions: Build configuration
  • Resolve: Module resolution settings
  • OptimizeDeps: Dependency optimization
  • And many more...

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Prereuisites

This repository builds with pantsbuild which requires Linux or Mac. If you're on a Windows, you can use WSL. Install pants using the provided instructions for your OS.

Development Setup

  1. Fork the repository and clone.
  2. Install dependencies: pants lock
  3. Optionally export a venv: pants venv. Creates dist/export/python/virtualenvs/python-default/3.X.Y.
  4. If you run pants venv you can update your IDE interpreter using the available venv.

Now you can make code changes as necessary.

Submitting a PR

Before you submit a PR, ensure the following run without errors:

  1. Run tests: pants test all
  2. Format code: pants fmt all
  3. Lint code: pants lint all

Links

FAQ

Q: Can I use this plugin with existing Vite plugins?

A: Yes! You can include any Vite plugin using the RawJS wrapper in the plugins array.

Q: How do I handle environment-specific configurations?

A: Use Python's environment variables and conditionals to create different configs for development/production.

Q: Can I override the default Reflex Vite configuration?

A: That depends. The plugin uses deep dict merging, so MOST of your configuration will override defaults but lists of items are concantenated rather than overridden. That being said, it is not recommended to override Reflex's defaults as it can break Reflex/Vite in unexpected ways.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

reflex_vite_config_plugin-0.0.4.tar.gz (52.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

reflex_vite_config_plugin-0.0.4-py3-none-any.whl (36.1 kB view details)

Uploaded Python 3

File details

Details for the file reflex_vite_config_plugin-0.0.4.tar.gz.

File metadata

File hashes

Hashes for reflex_vite_config_plugin-0.0.4.tar.gz
Algorithm Hash digest
SHA256 8d792da2b61067f02e7231b7838704d11ee0af0e2f2d9a4c97bc9d6f5204bd1e
MD5 7bac1d2391f53f5246ed0c6a6744c46d
BLAKE2b-256 c7b5ae0f93d23760d0671aec94b3a3e11908f0405b20dd5aa0ea730c4517dde2

See more details on using hashes here.

Provenance

The following attestation bundles were made for reflex_vite_config_plugin-0.0.4.tar.gz:

Publisher: publish.yaml on riebecj/reflex-vite-config-plugin

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file reflex_vite_config_plugin-0.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for reflex_vite_config_plugin-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 c3fa4e47ac76df695b692e232a3c64c3882d632cd10fdf28c23a3ff1e57dc7ae
MD5 2f9afa0a5169a128b51b797d7c30ed9e
BLAKE2b-256 5e34dc6b9ca5cdcaff2ed4f02948dd6142787d029ec16a367fc225c9f1a34268

See more details on using hashes here.

Provenance

The following attestation bundles were made for reflex_vite_config_plugin-0.0.4-py3-none-any.whl:

Publisher: publish.yaml on riebecj/reflex-vite-config-plugin

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page