[翻译]  What is the correct way to load CSS staticfiles using npm and Django?

[CHINESE]  使用npm和Django加载CSS静态文件的正确方法是什么?


I want to load my static css files (e.g., Bootstrap) from my node_modules directory, like so:

我想从我的node_modules目录加载我的静态css文件(例如,Bootstrap),如下所示:

{% load staticfiles %}
<link rel="stylesheet" href="{% static 'bootstrap/dist/css/bootstrap.min.css' %}" />

When I put .../node_modules/ in my STATICFILES_DIRS setting, this works. However, it also adds an absolutely massive number of files to my /static/ folder - mostly devDependencies that I don't need access to on the frontend.

当我在我的STATICFILES_DIRS设置中放置... / node_modules /时,这是有效的。但是,它还为我的/ static /文件夹添加了绝对大量的文件 - 主要是devDependencies,我不需要在前端访问。

What is the best practice for including certain static assets via npm, but not including everything from node_modules in my /static/ folder?

通过npm包含某些静态资产的最佳做法是什么,但不包括我/ static /文件夹中node_modules的所有内容?

Or, is it fine to include so many extraneous files and that's the best solution?

或者,包含这么多无关文件是否可以,这是最好的解决方案?

2 个解决方案

#1


1  

I personally think it's fine to have these extraneous dev files living in node_modules (and duplicated into STATIC_ROOT). Your mileage may vary if your node_modules folder is gigantic, but doubling the size isn't usually a big deal for my use cases, and it's convenient to not have to list each module in STATICFILES_DIRS as I install them.

我个人认为将这些无关的dev文件存放在node_modules中(并复制到STATIC_ROOT中)是很好的。如果你的node_modules文件夹很大,你的里程可能会有所不同,但是对于我的用例来说,加倍大小通常不是什么大问题,并且在安装它们时不必在STATICFILES_DIRS中列出每个模块。

STATICFILES_DIRS = (
    ...
    os.path.join(BASE_DIR, 'node_modules'),
    ...
)

Then in your templates, do:

然后在您的模板中,执行:

<script src='{% static 'bootstrap/dist/css/bootstrap.min.css' %}'></script>

If the folder ever did get out of hand size-wise, if you started encountering conflicts, or if there was a library you really didn't want to serve, Jostcrow's answer (or writing a custom staticfiles finder) could make sense.

如果文件夹大小失控,如果你开始遇到冲突,或者你真的不想服务的库,Jostcrow的答案(或编写自定义静态文件查找器)可能有意义。

Also, might be worth looking into trying to bundle everything together. If all of your stuff lives in bundled JS/CSS files, the whole issue is resolved by just webpack-ing those files into your app of choice.

此外,可能值得考虑尝试将所有内容捆绑在一起。如果您的所有内容都存在于捆绑的JS / CSS文件中,那么只需将这些文件通过webpack打包到您选择的应用程序中即可解决整个问题。

#2


0  

What I do is the following,

我做的是以下,

STATICFILES_DIRS = (
    os.path.join(DJANGO_PROJECT_DIR, 'static'),
    os.path.join(ROOT_DIR, 'node_modules', 'd3', 'build'),
    os.path.join(ROOT_DIR, 'node_modules', 'c3'),
)

This will place only the needed files in my static folder.

这将只将所需文件放在我的静态文件夹中。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号