Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/getting_started/project-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ The `assets` directory is where you can store any static assets you want to be p

Reflex copies these files into `.web/public` during compilation. Deleting or renaming an asset removes its previous copy on the next compile, including production exports, while preserving public files generated by plugins. If another process has changed a copied file, Reflex preserves that replacement. Files already deleted before upgrading to a version with asset tracking require a one-time removal of the stale copies or a clean `.web` directory.

`rx.Config(assets_dir=...)` and `rx.Config(lockfile_dir=...)` move the `assets` and `reflex.lock` directories, to a path relative to the project root or an absolute one. This lets two apps that share a root keep their own assets and frontend lockfiles (and their own `.web` with `REFLEX_WEB_WORKDIR`):

```python
from pathlib import Path

import reflex as rx

config = rx.Config(
Comment thread
benedikt-bartscher marked this conversation as resolved.
Resolved
app_name="website",
assets_dir=Path("website/assets"),
lockfile_dir=Path("website/reflex.lock"),
)
```

For example, if you save an image to `assets/image.png` you can display it from your app like this:

```python
Expand Down
1 change: 1 addition & 0 deletions news/+app-assets-and-lockfile-dirs.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`rx.Config(assets_dir=...)` and `rx.Config(lockfile_dir=...)` move an app's `assets` and `reflex.lock` directories, so apps that share a project root each ship only their own assets and keep their own frontend lockfiles: `rx.Config(app_name="website", assets_dir=Path("website/assets"), lockfile_dir=Path("website/reflex.lock"))`.
Comment thread
benedikt-bartscher marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`Config` has `assets_dir` and `lockfile_dir`, defaulting to `assets` and `reflex.lock` under the app root.
11 changes: 11 additions & 0 deletions packages/reflex-base/src/reflex_base/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,8 @@ class BaseConfig:
telemetry_enabled: Telemetry opt-in.
bun_path: The bun path.
frozen_lockfile: Run frontend package manager in lockfile-enforcing mode (only honored by bun).
lockfile_dir: The directory that keeps the frontend's package.json and lockfiles between builds, to commit with the app. Relative to the app root. Lets apps that share a root keep their own lockfiles.
assets_dir: The directory of the static files copied into the frontend and served from its root, which `rx.asset` and local stylesheets resolve against. Relative to the app root. Lets apps that share a root ship only their own assets.
static_page_generation_timeout: Timeout to do a production build of a frontend page.
cors_allowed_origins: Comma separated list of origins that are allowed to connect to the backend API. The default allows any origin in dev mode; in prod mode it allows the backend's own origin and, when deploy_url is set, the origin of deploy_url.
vite_allowed_hosts: Allowed hosts for the Vite dev server. Set to True to allow all hosts, or provide a list of hostnames (e.g. ["myservice.local"]) to allow specific ones. Prevents 403 errors in Docker, Codespaces, reverse proxies, etc.
Expand Down Expand Up @@ -242,6 +244,10 @@ class BaseConfig:

frozen_lockfile: bool = True

lockfile_dir: Path = Path(constants.Bun.ROOT_LOCKFILE_DIR)

assets_dir: Path = Path(constants.Dirs.APP_ASSETS)

static_page_generation_timeout: int = 60

cors_allowed_origins: Annotated[
Expand Down Expand Up @@ -672,6 +678,8 @@ def _normalize_frontend_compression_formats(self):
def _normalize_paths(self):
"""Ensure frontend and backend paths start with a slash if provided.

Directories given as strings become ``Path`` objects.

Raises:
ConfigError: If a frontend_path segment is not a plain directory name.
"""
Expand All @@ -696,6 +704,9 @@ def _normalize_paths(self):
if self.backend_path and not self.backend_path.startswith("/"):
self.backend_path = f"/{self.backend_path}"

self.lockfile_dir = Path(self.lockfile_dir)
self.assets_dir = Path(self.assets_dir)

def _add_builtin_plugins(self):
"""Add the builtin plugins to the config."""
for plugin in _PLUGINS_ENABLED_BY_DEFAULT:
Expand Down
9 changes: 4 additions & 5 deletions reflex/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def remove_stale_external_asset_symlinks():
re-creation during import.
"""
external_dir = (
Path.cwd() / constants.Dirs.APP_ASSETS / constants.Dirs.EXTERNAL_APP_ASSETS
Path.cwd() / get_config().assets_dir / constants.Dirs.EXTERNAL_APP_ASSETS
)
if not external_dir.exists():
return
Expand Down Expand Up @@ -324,13 +324,12 @@ def asset(
FileNotFoundError: If the file does not exist.
ValueError: If subfolder is provided for local assets.
"""
assets = constants.Dirs.APP_ASSETS
assets = Path.cwd() / get_config().assets_dir
backend_only = EnvironmentVariables.REFLEX_BACKEND_ONLY.get()

# Local asset handling
if not shared:
cwd = Path.cwd()
src_file_local = cwd / assets / path
src_file_local = assets / path
if subfolder is not None:
msg = "Subfolder is not supported for local assets."
raise ValueError(msg)
Expand Down Expand Up @@ -361,7 +360,7 @@ def asset(
# Symlink the asset to the app's external assets directory if running frontend.
if not backend_only:
# Create the asset folder in the currently compiling app.
asset_folder = Path.cwd() / assets / external / subfolder
asset_folder = assets / external / subfolder
asset_folder.mkdir(parents=True, exist_ok=True)

_link_shared_asset(asset_folder / path, src_file_shared)
Comment thread
benedikt-bartscher marked this conversation as resolved.
Resolved
Expand Down
2 changes: 1 addition & 1 deletion reflex/compiler/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ def _compile_root_stylesheet(
])

failed_to_import_sass = False
assets_app_path = Path.cwd() / constants.Dirs.APP_ASSETS
assets_app_path = Path.cwd() / get_config().assets_dir

stylesheets_files: list[Path] = []
stylesheets_urls = []
Expand Down
3 changes: 2 additions & 1 deletion reflex/compiler/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
MemoFunctionDefinition,
MemoParamKind,
)
from reflex_base.config import get_config
from reflex_base.constants.state import FIELD_MARKER
from reflex_base.registry import RegistrationContext
from reflex_base.style import Style
Expand Down Expand Up @@ -1276,7 +1277,7 @@ def _sync_app_assets() -> None:
Raises:
OSError: If the source cannot be scanned or the output cannot be updated.
"""
assets = Path(constants.Dirs.APP_ASSETS)
assets = get_config().assets_dir
web_dir = get_web_dir()
public = web_dir / constants.Dirs.PUBLIC
manifest_path = web_dir / _ASSET_MANIFEST_FILENAME
Expand Down
10 changes: 6 additions & 4 deletions reflex/utils/exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,8 @@ def get_reload_paths() -> Sequence[Path]:
if path.exists()
)

lockfile_dir = Path.cwd() / config.lockfile_dir

def is_excluded_by_default(path: Path) -> bool:
if path.is_dir():
if path.name.startswith("."):
Expand All @@ -717,10 +719,8 @@ def is_excluded_by_default(path: Path) -> bool:
if path.name.startswith("__"):
# ignore things like __pycache__
return True
return path.name in (
".gitignore",
"uploaded_files",
constants.Bun.ROOT_LOCKFILE_DIR,
return path.name in (".gitignore", "uploaded_files") or (
path.absolute() == lockfile_dir
)

reload_paths = (
Expand Down Expand Up @@ -771,6 +771,8 @@ def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel):


HOTRELOAD_IGNORE_EXTENSIONS = (
# Watched lockfile dirs: nested ones and those of other apps sharing the root.
"lock",
"txt",
"toml",
"sqlite",
Expand Down
43 changes: 38 additions & 5 deletions reflex/utils/frontend_skeleton.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import json
import logging
import os
import uuid
from pathlib import Path
from typing import Literal
Expand All @@ -20,16 +21,39 @@
logger = logging.getLogger(__name__)


def _external_assets_gitignore_entry() -> str | None:
"""Get the gitignore entry for the shared asset links in the configured assets dir.

Returns:
The entry relative to the app root, or None if the assets dir lies outside it.
"""
root = Path.cwd()
external_dir = Path(
os.path.normpath(
root / get_config().assets_dir / constants.Dirs.EXTERNAL_APP_ASSETS
)
)
if not external_dir.is_relative_to(root):
return None
return f"{external_dir.relative_to(root).as_posix()}/"


def initialize_gitignore(
gitignore_file: Path = constants.GitIgnore.FILE,
files_to_ignore: set[str] | list[str] = constants.GitIgnore.DEFAULTS,
files_to_ignore: set[str] | list[str] | None = None,
):
"""Initialize the template .gitignore file.

Args:
gitignore_file: The .gitignore file to create.
files_to_ignore: The files to add to the .gitignore file.
files_to_ignore: The files to add to the .gitignore file, by default Reflex's own and the shared asset links of the configured assets dir.
"""
if files_to_ignore is None:
external_assets = _external_assets_gitignore_entry()
files_to_ignore = constants.GitIgnore.DEFAULTS | (
{external_assets} if external_assets else set()
)

# Combine with the current ignored files.
current_ignore: list[str] = []
if gitignore_file.exists():
Expand Down Expand Up @@ -277,16 +301,25 @@ def initialize_requirements_txt(
NO_PRUNE_LOCKFILE_NAMES: tuple[str, ...] = (constants.PackageJson.PATH,)


def get_root_lockfile_dir() -> Path:
"""Get the directory the frontend lockfiles persist in, ``reflex.lock`` by default.

Returns:
The configured ``lockfile_dir`` under the app root.
"""
return Path.cwd() / get_config().lockfile_dir


def get_root_lockfile_path(filename: str) -> Path:
"""Get a persisted lockfile path under the app root's reflex.lock dir.
"""Get a persisted lockfile path under the app's lockfile directory.

Args:
filename: The lockfile basename (e.g. ``bun.lock``, ``package-lock.json``).

Returns:
The lockfile path inside ``<cwd>/reflex.lock/``.
The lockfile path inside the configured ``lockfile_dir``.
"""
return Path.cwd() / constants.Bun.ROOT_LOCKFILE_DIR / filename
return get_root_lockfile_dir() / filename


def get_web_lockfile_path(filename: str) -> Path:
Expand Down
6 changes: 3 additions & 3 deletions reflex/utils/js_runtimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def _persisted_lockfile_implies_npm() -> bool:
Returns:
Whether the persisted state implies npm.
"""
root_dir = Path.cwd() / constants.Bun.ROOT_LOCKFILE_DIR
root_dir = frontend_skeleton.get_root_lockfile_dir()
return (root_dir / constants.Node.LOCKFILE_PATH).exists() and not (
root_dir / constants.Bun.LOCKFILE_PATH
).exists()
Expand Down Expand Up @@ -144,7 +144,7 @@ def prefer_npm_over_bun() -> bool:
if explicit is not None:
return explicit
if _persisted_lockfile_implies_npm():
_log_implicit_npm_notice(Path.cwd() / constants.Bun.ROOT_LOCKFILE_DIR)
_log_implicit_npm_notice(frontend_skeleton.get_root_lockfile_dir())
return True
return False

Expand Down Expand Up @@ -553,7 +553,7 @@ def _run_initial_install(
return

if any("lockfile had changes, but lockfile is frozen" in line for line in logs):
root_dir = Path.cwd() / constants.Bun.ROOT_LOCKFILE_DIR
root_dir = frontend_skeleton.get_root_lockfile_dir()
logger.error(
"The persisted lockfile is out of sync with the recovered "
f"package.json. Delete the [bold]{escape(str(root_dir))}[/bold] directory "
Expand Down
Loading
Loading