css - Django + Svelte 样式不起作用,MIME 类型('text/html')不是受支持的样式表 MIME 类型
问题描述
我正在尝试将我的 Django 应用程序连接到 Svelte 前端。我将模板查找器定向到build
Svelte 文件夹的目录。我不会使用 Django 的模板功能,只会使用带有 Svelte 前端的 DRF,这样我就不需要这些功能。我只想让 Django 提供已编译的文件。
TEMPLATES = [
{
...
'DIRS': [
BASE_DIR / '../frontend/public/'
],
...
},
]
然后在我看来,我可以使用:
urlpatterns = [
path('', TemplateView.as_view(template_name="index.html"))
]
当我在 localhost:8000 上打开我的主视图时,它加载index.html
就好了。唯一的问题是我的样式没有被加载。这是文件夹结构:
backend
app
settings.py
frontend
public
build
bundle.js
bundle.css
index.html
global.css
正如我STATIC_ROOT
和STATIC_URL
我使用这个:
STATIC_URL = '/build/'
STATIC_ROOT = BASE_DIR / '../frontend/public/'
这也很好用,如果我使用python3 manage.py collectstatic
我的build
目录中的管理样式,我可以完全访问 Django 管理。
但是,当我尝试访问我的开发服务器上的主页时,我的控制台中出现以下错误:
拒绝应用来自 'http://localhost:8000/global.css' 的样式,因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。
这是 index.html 的内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Svelte app</title>
<link rel='icon' type='image/png' href='/favicon.png'>
<link rel='stylesheet' href='/global.css'>
<link rel='stylesheet' href='/build/bundle.css'>
<script defer src='/build/bundle.js'></script>
</head>
<body>
</body>
</html>
我在 Google 上搜索并尝试在样式引用上添加或删除 / ,但不幸的是,这现在也起作用了。
为什么我会收到这些错误?如何确保 Djangobuild
正确加载目录中的样式?
解决方案
我遇到了相同的“MIME 类型('text/html')不可执行”问题,我使用 django 静态模板标签修复了它,为了使其正常工作,我做了这些更改。
在 settings.py
TEMPLATES = [
{
...
'DIRS': ['./frontend/public'],
'APP_DIRS': False,
...
},
]
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR /"frontend/public",
]
view.py 很好
文件夹结构:
backend
app
settings.py
frontend
public
build
bundle.js
bundle.css
index.html
global.css
在您的 svelte index.html 中,使用 django 静态模板标签 {% load static %} 和 {% static 'path' %} 来构建 URL。
前端/公共/index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- building urls using static tag -->
<link rel='icon' type='image/png' href='{% static '/favicon.png'%}'>
<link rel='stylesheet' href=' {% static 'global.css' %} '>
<link rel='stylesheet' href='{% static '/build/bundle.css' %}'>
<script defer src='{% static '/build/bundle.js' %}'></script>
</head>
<body>
</body>
</html>
文档:管理静态文件