Complete API documentation for Flask-Vite.
The main Flask extension class.
class Vite:
def __init__(
self,
app: Flask | None = None,
vite_routes_host: str | None = None
) -> NoneParameters:
app(Flask, optional): Flask application instancevite_routes_host(str, optional): Host for serving Vite assets when using host matching
Example:
from flask import Flask
from flask_vite import Vite
app = Flask(__name__)
vite = Vite(app)
# Or using factory pattern
vite = Vite()
vite.init_app(app)Initialize the extension with a Flask application.
def init_app(
self,
app: Flask,
vite_routes_host: str | None = None
) -> NoneParameters:
app(Flask): Flask application instancevite_routes_host(str, optional): Host for serving Vite assets
Raises:
ViteError: If extension is already registered or configuration is invalid
Example:
app = Flask(__name__)
vite = Vite()
vite.init_app(app, vite_routes_host='cdn.example.com')Serve built Vite assets in production mode.
def vite_static(
self,
filename: str,
vite_routes_host: str | None = None
) -> ResponseParameters:
filename(str): Asset filename to servevite_routes_host(str, optional): Host parameter for host matching
Returns:
Response: Flask response object with the static file
Note: This method is automatically registered as a Flask route handler for /_vite/<path:filename>.
Auto-inject Vite tags into HTML responses when VITE_AUTO_INSERT is enabled.
def after_request(self, response: Response) -> ResponseParameters:
response(Response): Flask response object
Returns:
Response: Modified response with injected Vite tags
Note: This method is automatically registered when VITE_AUTO_INSERT=True.
Path to the Vite project directory.
@property
def vite_folder_path(self) -> strReturns:
str: Path to Vite folder (default: "vite")
NPM wrapper instance for running npm commands.
@property
def npm(self) -> NPM | NoneReturns:
NPM | None: NPM wrapper instance
Flask-Vite uses Flask's configuration system. Set these variables in your Flask config:
Type: bool
Default: False
Automatically inject Vite asset tags into HTML responses.
app.config['VITE_AUTO_INSERT'] = TrueWhen enabled, Flask-Vite automatically injects {{ vite_tags() }} into HTML responses before the closing </head> tag.
Type: str
Default: "vite"
Path to the Vite project directory relative to the Flask app root.
app.config['VITE_FOLDER_PATH'] = 'frontend'Type: str
Default: "npm"
Path to the npm binary executable.
app.config['VITE_NPM_BIN_PATH'] = '/usr/local/bin/npm'Generate HTML tags for including Vite assets.
def vite_tags(*, static: bool = False) -> MarkupParameters:
static(bool, optional): Force production mode tags regardless of Flask debug mode
Returns:
Markup: Safe HTML markup containing script and link tags
Template Usage:
<!-- In development (Flask debug mode) -->
{{ vite_tags() }}
<!-- Outputs: -->
<!-- <script type="module" src="http://localhost:3000/@vite/client"></script> -->
<!-- <script type="module" src="http://localhost:3000/main.js"></script> -->
<!-- In production (Flask production mode) -->
{{ vite_tags() }}
<!-- Outputs: -->
<!-- <script type="module" src="/_vite/index-abc123.js"></script> -->
<!-- <link rel="stylesheet" href="/_vite/index-abc123.css"></link> -->All CLI commands are available under the flask vite command group.
Initialize a new Vite project directory.
flask vite initDescription: Creates a new Vite project in the configured directory with starter files including package.json, vite.config.js, and main.js.
Behavior:
- Copies starter files from the extension's template
- Fails if target directory already exists
- Uses
VITE_FOLDER_PATHconfiguration
Install npm dependencies.
flask vite installDescription: Runs npm install in the Vite project directory.
Equivalent to: npm install
Start Vite development server.
flask vite startDescription: Starts Vite in development mode with hot reloading.
Equivalent to: npm run dev
Build assets for production.
flask vite buildDescription: Builds optimized assets for production deployment.
Equivalent to: npm run build
Check for outdated dependencies.
flask vite check-updatesDescription: Lists outdated npm packages.
Equivalent to: npm outdated
Update dependencies.
flask vite updateDescription: Updates npm dependencies to their latest versions.
Equivalent to: npm update
Wrapper class for executing npm commands.
@dataclass
class NPM:
cwd: str = ""
npm_bin_path: str = "npm"Parameters:
cwd(str): Working directory for npm commandsnpm_bin_path(str): Path to npm executable
Execute npm command with given arguments.
def run(self, *args: str) -> NoneParameters:
*args(str): Command arguments to pass to npm
Raises:
NPMError: If npm command fails or npm is not found
Example:
npm = NPM(cwd="/path/to/vite", npm_bin_path="npm")
npm.run("install") # Equivalent to: npm install
npm.run("run", "build") # Equivalent to: npm run buildBase exception for Flask-Vite errors.
class ViteError(ValueError):
passRaised when:
- Extension is already registered on a Flask app
- Invalid configuration is provided
- Host matching configuration errors
Exception for npm-related errors.
class NPMError(Exception):
passRaised when:
- npm binary is not found
- npm command execution fails
- Working directory is invalid
For Flask applications using host_matching=True:
app = Flask(__name__)
app.url_map.host_matching = True
# Serve assets from specific host
vite = Vite(app, vite_routes_host='static.example.com')
# Or serve from same host as request (wildcard)
vite = Vite(app, vite_routes_host='*')Override the default asset serving behavior:
from flask_vite import Vite
class CustomVite(Vite):
def vite_static(self, filename, vite_routes_host=None):
# Custom asset serving logic
return custom_serve_file(filename)
vite = CustomVite(app)Flask-Vite works seamlessly with Flask blueprints:
from flask import Blueprint, render_template
bp = Blueprint('main', __name__)
@bp.route('/')
def index():
return render_template('index.html') # Uses {{ vite_tags() }}While not common, you can register multiple Vite instances with different configurations:
# Not recommended - Flask-Vite is designed as a singleton extension
# Each instance would overwrite the previous one in app.extensions['vite']Flask-Vite is fully typed. Import types for enhanced IDE support:
from flask_vite import Vite
from flask_vite.npm import NPM, NPMError
from flask_vite.extension import ViteError
# All classes and functions include proper type annotations