缩小目录中的所有CSS和Javascript

2024-04-25 09:59:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个python脚本,它将打包目录的内容并缩小所有JavaScript和CSS脚本。在

如果我使用下面的代码(文章的底部),并且theme_files中的目录结构是这样的:

\
 |-assets\
 |        |-css\
 |        |     |-theme.css
 |        |     |-stylesheet.css
 |        |
 |        |-js\
 |        |    |-theme.js
 |        |    |-page.js
 |
 |-index.html

(有更好的方法吗?)

它会将整个目录结构正确地输出到生成的.pak文件中。但是,缩小后的css和javascript文件除了它们自己的文件名之外没有其他内容。在

示例:文件的内容(假设是缩小的)theme.css将是“主题.css““

就这样。没别的了。一条线。在

你知道我做错什么了吗?在


^{pr2}$

Tags: 文件代码目录脚本内容文章jsfiles
2条回答

如果您需要缩小(或/或合并)JS/CSS文件:我创建了Minifpy:一个使用Python合并和缩小JS和CSS文件的工具。在

Minifpy使用非常简单的JSON配置文件来定义文件是否必须合并、缩小:

{
    "js": {
        "minify_files": [
            {"from": "static/file.js", "to":"static/file.min.js"},
        ],
        "merge_files": [
            {"from" : ["static/file1.js", "static/file2.js"], "to":"static/public.js", "to_min": "static/public.min.js"}
        ]
    },
    "css" : {
        "minify_files": [
            {"from": "static/file.css", "to":"static/file.min.css"},
        ],
        "merge_files": [
            {"from" : ["static/file1.css", "static/file2.css"], "to":"static/public.css", "to_min": "static/public.min.css"}
        ]
    }
}

但是Minifpy不能自动缩小项目中的每个文件。在

Minifpy检测JS/CSS文件的任何修改,并自动合并/缩小它们(对开发很有用)。在

正如@Squall所说

rcssmin.cssmin() and rjsmin.jsmin() expect the first element to be the CSS respectively JS code to minify as string. You have to open and read the CSS and JS files by yourself.


if filename.endswith(".css"):
    with open(os.path.join(dirname, filename), "r") as assetfile:
        assetdata = assetfile.read().replace("\n", "")
    cssMinified = io.StringIO()
    cssMinified.write(rcssmin.cssmin(assetdata, keep_bang_comments=True))
    themePak.writestr(os.path.join(dirname, filename), cssMinified.getvalue())

if filename.endswith(".js"):
    with open(os.path.join(dirname, filename), "r") as assetfile:
        assetdata = assetfile.read().replace("\n", "")
    jsMinified = io.StringIO()
    jsMinified.write(rjsmin.jsmin(assetdata, keep_bang_comments=True))
    themePak.writestr(os.path.join(dirname, filename), jsMinified.getvalue())

上面代码中我的if语句中的更改将资产文件作为字符串打开,然后将它们传递给缩小。在

我学到了一个艰难的方法,你必须确保os.path.join()文件名和目录。在

^{pr2}$

然后缩小assetdata并写入文件。(在本例中,是内存对象。)

相关问题 更多 >