Skip to content

Commit b5a33c5

Browse files
authored
Merge pull request #4105 from Thanatos9404/fix-assets-css-extension
Only link `.css` files in assets as stylesheets
2 parents 443f713 + c1bd1df commit b5a33c5

4 files changed

Lines changed: 141 additions & 47 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).
1010
### Fixed
1111
- [#4136](https://github.com/plotly/dash/pull/4136) MCP tools with a generic type annotation such as `list[str]` no longer crash on Python 3.10.
1212
- [#4114](https://github.com/plotly/dash/pull/4114) Fix the `get_dash_component` MCP tool failing when a component's value contains Dash components, Plotly figures, or numpy arrays. Fixes [#4113](https://github.com/plotly/dash/issues/4113).
13+
- [#4105](https://github.com/plotly/dash/pull/4105) Only load `.js`/`.mjs` assets as scripts and `.css` assets as stylesheets, at startup and on hot reload. Hot reload now skips files excluded by `assets_ignore` or `assets_path_ignore`. Fixes [#1684](https://github.com/plotly/dash/issues/1684).
1314

1415
## [4.5.0] - 2026-10-29
1516

‎dash/dash-renderer/src/components/core/Reloader.react.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ class Reloader extends React.Component {
109109
let was_css = false;
110110
// eslint-disable-next-line prefer-const
111111
for (let a of reloadRequest.content.files) {
112-
if (a.is_css) {
112+
if (a.type === 'css') {
113113
was_css = true;
114114
const nodesToDisable = [];
115115

‎dash/dash.py‎

Lines changed: 55 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,12 @@
177177
except: # noqa: E722
178178
page_container = None
179179

180+
_ASSET_TYPES = {".js": "js", ".mjs": "mjs", ".css": "css"}
181+
182+
183+
def _asset_type(filename):
184+
return _ASSET_TYPES.get(os.path.splitext(filename)[1])
185+
180186

181187
def _get_traceback(secret, error: Exception):
182188
try:
@@ -1424,7 +1430,7 @@ def _relative_url_path(relative_package_path="", namespace=""):
14241430
static_url = self.get_asset_url(resource["asset_path"])
14251431
url_with_cache = static_url + f"?m={resource['ts']}"
14261432
# Import .mjs files with type=module script tag
1427-
if static_url.endswith(".mjs"):
1433+
if _asset_type(resource["asset_path"]) == "mjs":
14281434
attrs = {url_attr: url_with_cache, "type": "module"}
14291435
if "attributes" in resource:
14301436
attrs.update(resource["attributes"])
@@ -1983,17 +1989,21 @@ def _add_assets_resource(self, url_path, file_path):
19831989
self._assets_files.append(file_path)
19841990
return res
19851991

1992+
def _is_ignored_asset(self, folders, filename):
1993+
# folders: the folder names between the assets folder and the file.
1994+
ignore_str = self.config.assets_ignore
1995+
if ignore_str and re.search(ignore_str, filename):
1996+
return True
1997+
return any(
1998+
re.search(ignore_path, folder)
1999+
for ignore_path in (self.config.assets_path_ignore or [])
2000+
if ignore_path
2001+
for folder in folders
2002+
)
2003+
19862004
def _walk_assets_directory(self):
19872005
walk_dir = self.config.assets_folder
19882006
slash_splitter = re.compile(r"[\\/]+")
1989-
ignore_str = self.config.assets_ignore
1990-
ignore_path_list = self.config.assets_path_ignore
1991-
ignore_filter = re.compile(ignore_str) if ignore_str else None
1992-
ignore_path_filters = [
1993-
re.compile(ignore_path)
1994-
for ignore_path in (ignore_path_list or [])
1995-
if ignore_path
1996-
]
19972007

19982008
for current, _, files in sorted(os.walk(walk_dir)):
19992009
if current == walk_dir:
@@ -2007,32 +2017,23 @@ def _walk_assets_directory(self):
20072017
else:
20082018
base = splitted[0]
20092019

2010-
# Check if any level of current path matches ignore path
2011-
if s and any(
2012-
ignore_path_filter.search(x)
2013-
for ignore_path_filter in ignore_path_filters
2014-
for x in s.split(os.path.sep)
2015-
):
2016-
pass
2017-
else:
2018-
if ignore_filter:
2019-
files_gen = (x for x in files if not ignore_filter.search(x))
2020-
else:
2021-
files_gen = files
2020+
folders = s.split(os.path.sep) if s else []
2021+
2022+
for f in sorted(files):
2023+
if self._is_ignored_asset(folders, f):
2024+
continue
20222025

2023-
for f in sorted(files_gen):
2024-
path = "/".join([base, f]) if base else f
2026+
path = "/".join([base, f]) if base else f
20252027

2026-
full = os.path.join(current, f)
2028+
full = os.path.join(current, f)
2029+
asset_type = _asset_type(f)
20272030

2028-
if f.endswith("js"):
2029-
self.scripts.append_script(
2030-
self._add_assets_resource(path, full)
2031-
)
2032-
elif f.endswith("css"):
2033-
self.css.append_css(self._add_assets_resource(path, full)) # type: ignore[reportArgumentType]
2034-
elif f == "favicon.ico":
2035-
self._favicon = path
2031+
if asset_type in ("js", "mjs"):
2032+
self.scripts.append_script(self._add_assets_resource(path, full))
2033+
elif asset_type == "css":
2034+
self.css.append_css(self._add_assets_resource(path, full)) # type: ignore[reportArgumentType]
2035+
elif f == "favicon.ico":
2036+
self._favicon = path
20362037

20372038
@staticmethod
20382039
def _invalid_resources_handler(err):
@@ -2512,33 +2513,41 @@ def enable_dev_tools( # pylint: disable=too-many-branches
25122513
# noinspection PyProtectedMember
25132514
def _on_assets_change(self, filename, modified, deleted):
25142515
_reload = self._hot_reload
2516+
in_assets = self.config.assets_folder in filename
2517+
asset_path = ""
2518+
if in_assets:
2519+
asset_path = (
2520+
os.path.relpath(
2521+
filename,
2522+
os.path.commonprefix([self.config.assets_folder, filename]),
2523+
)
2524+
.replace("\\", "/")
2525+
.lstrip("/")
2526+
)
2527+
*folders, name = asset_path.split("/")
2528+
if self._is_ignored_asset(folders, name):
2529+
return
2530+
25152531
with _reload.lock:
25162532
_reload.hard = True
25172533
_reload.hash = generate_hash()
25182534

2519-
if self.config.assets_folder in filename:
2520-
asset_path = (
2521-
os.path.relpath(
2522-
filename,
2523-
os.path.commonprefix([self.config.assets_folder, filename]),
2524-
)
2525-
.replace("\\", "/")
2526-
.lstrip("/")
2527-
)
2535+
if in_assets:
2536+
asset_type = _asset_type(filename)
25282537

25292538
_reload.changed_assets.append(
25302539
{
25312540
"url": self.get_asset_url(asset_path),
25322541
"modified": int(modified),
2533-
"is_css": filename.endswith("css"),
2542+
"type": asset_type,
25342543
}
25352544
)
25362545

25372546
if filename not in self._assets_files and not deleted:
25382547
res = self._add_assets_resource(asset_path, filename)
2539-
if filename.endswith("js"):
2548+
if asset_type in ("js", "mjs"):
25402549
self.scripts.append_script(res)
2541-
elif filename.endswith("css"):
2550+
elif asset_type == "css":
25422551
self.css.append_css(res) # type: ignore[reportArgumentType]
25432552

25442553
if deleted:
@@ -2554,10 +2563,10 @@ def delete_resource(resources):
25542563
if to_delete:
25552564
resources.remove(to_delete)
25562565

2557-
if filename.endswith("js"):
2566+
if asset_type in ("js", "mjs"):
25582567
# pylint: disable=protected-access
25592568
delete_resource(self.scripts._resources._resources)
2560-
elif filename.endswith("css"):
2569+
elif asset_type == "css":
25612570
# pylint: disable=protected-access
25622571
delete_resource(self.css._resources._resources)
25632572

‎tests/unit/test_resources.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
import re
23
import sys
34

45
import mock
@@ -286,3 +287,86 @@ def test_index_with_windows_extended_length_paths(tmp_path, monkeypatch):
286287
assert "/_dash-component-suites/dash/deps/polyfill@" in body
287288
assert "dash-stream-worker.v" in body
288289
assert "/assets/icons/favicon.ico?m=" in body
290+
291+
292+
def test_index_loads_assets_by_extension(tmp_path):
293+
assets = tmp_path / "assets"
294+
assets.mkdir()
295+
for name in (
296+
"style.css",
297+
"theme.scss",
298+
"app.js",
299+
"app.mjs",
300+
"bundle.cjs",
301+
"nodejs",
302+
):
303+
(assets / name).write_text("")
304+
305+
app = dash.Dash(__name__, assets_folder=str(assets))
306+
app.layout = html.Div()
307+
308+
body = app.server.test_client().get("/").get_data(as_text=True)
309+
310+
assert '<link rel="stylesheet" href="/assets/style.css?m=' in body
311+
assert '<script src="/assets/app.js?m=' in body
312+
assert re.search(r'<script src="/assets/app\.mjs\?m=[^"]*" type="module">', body)
313+
for name in ("theme.scss", "bundle.cjs", "/assets/nodejs"):
314+
assert name not in body
315+
316+
317+
def test_hot_reload_uses_asset_type(tmp_path):
318+
assets = tmp_path / "assets"
319+
assets.mkdir()
320+
app = dash.Dash(__name__, assets_folder=str(assets))
321+
322+
for name in ("style.css", "theme.scss", "app.mjs", "bundle.cjs"):
323+
path = assets / name
324+
path.write_text("")
325+
app._on_assets_change(str(path), path.stat().st_mtime, False)
326+
327+
assert [
328+
(asset["url"], asset["type"]) for asset in app._hot_reload.changed_assets
329+
] == [
330+
("/assets/style.css", "css"),
331+
("/assets/theme.scss", None),
332+
("/assets/app.mjs", "mjs"),
333+
("/assets/bundle.cjs", None),
334+
]
335+
assert [r["asset_path"] for r in app.css._resources._resources] == ["style.css"]
336+
assert [r["asset_path"] for r in app.scripts._resources._resources] == ["app.mjs"]
337+
338+
for name in ("style.css", "app.mjs"):
339+
app._on_assets_change(str(assets / name), 0, True)
340+
assert app.css._resources._resources == []
341+
assert app.scripts._resources._resources == []
342+
343+
344+
def test_hot_reload_skips_ignored_assets(tmp_path):
345+
assets = tmp_path / "assets"
346+
(assets / "drafts").mkdir(parents=True)
347+
app = dash.Dash(
348+
__name__,
349+
assets_folder=str(assets),
350+
assets_ignore=r".*\.scss$|^ignored",
351+
assets_path_ignore=["drafts"],
352+
)
353+
reload_hash = app._hot_reload.hash
354+
355+
for name in ("theme.scss", "ignored.css", "drafts/draft.css"):
356+
path = assets / name
357+
path.write_text("")
358+
app._on_assets_change(str(path), path.stat().st_mtime, False)
359+
app._on_assets_change(str(path), -1, True)
360+
361+
assert app._hot_reload.hash == reload_hash
362+
assert app._hot_reload.changed_assets == []
363+
assert app.css._resources._resources == []
364+
365+
path = assets / "style.css"
366+
path.write_text("")
367+
app._on_assets_change(str(path), path.stat().st_mtime, False)
368+
369+
assert app._hot_reload.hash != reload_hash
370+
assert [asset["url"] for asset in app._hot_reload.changed_assets] == [
371+
"/assets/style.css"
372+
]

0 commit comments

Comments
 (0)