迁移至/app目录后Django-webpack-loader的render_bundle报错求助
Django-webpack-loader迁移后render_bundle报错解决
我们有一个基于Django-webpack-loader的遗留Django-webpack应用,将代码迁移至/app目录后,render_bundle功能失效,报错如下:
File "/usr/local/lib/python3.9/site-packages/webpack_loader/templatetags/webpack_loader.py", line 22, in render_bundle tags = utils.get_as_tags( File "/usr/local/lib/python3.9/site-packages/webpack_loader/utils.py", line 71, in get_as_tags bundle = _get_bundle(loader, bundle_name, extension) File "/usr/local/lib/python3.9/site-packages/webpack_loader/utils.py", line 47, in _get_bundle bundle = loader.get_bundle(bundle_name) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 116, in get_bundle filtered_chunks = self.filter_chunks(chunks) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 58, in filter_chunks ignore = any(regex.match(chunk) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 58, in <genexpr> ignore = any(regex.match(chunk) TypeError: expected string or bytes-like object
版本信息
- django-webpack-loader: 1.6.0
- webpack-bundle-tracker: 0.4.3
webpack-stats.json内容
{"status":"done","publicPath":"http://localhost:8001/","chunks":{"app":[{"name":"app.js","publicPath":"http://localhost:8001/app.js","path":"/app/static/dist/app.js"}]}}
Django配置
BASE_DIR = "/app" STATIC_URL = "/app/static/dist/" STATIC_ROOT = Path(BASE_DIR, "public") STATICFILES_DIRS = [ Path(BASE_DIR, "static"), Path(BASE_DIR, "static", "dist"), ] WEBPACK_LOADER = {"DEFAULT": {"CACHE": not DEBUG}}
触发报错的代码
{% render_bundle 'app' %}
问题原因
webpack-bundle-tracker 0.4.3生成的webpack-stats.json中,chunks下的每个bundle对应的是chunk对象数组,而django-webpack-loader 1.6.0的filter_chunks方法直接将chunk对象传入正则匹配,导致类型错误(正则期望字符串/字节对象,实际传入字典)。
解决方案
方案1:修改webpack-bundle-tracker配置生成旧格式统计文件
在webpack配置中给BundleTracker添加format: 'legacy'选项,让其生成兼容旧版django-webpack-loader的统计格式:
const BundleTracker = require('webpack-bundle-tracker'); const path = require('path'); module.exports = { // ...其他webpack配置 plugins: [ new BundleTracker({ path: path.join(__dirname, '/app'), // 对应stats文件生成目录 filename: 'webpack-stats.json', format: 'legacy' // 启用旧格式 }) ] };
生成的stats文件中chunks结构会变为{"app": ["app.js"]},符合django-webpack-loader 1.6.0的处理逻辑。
方案2:升级django-webpack-loader至兼容版本
将django-webpack-loader升级到2.x或3.x版本(这些版本已适配webpack-bundle-tracker 0.4.x的新格式),执行升级命令:
pip install django-webpack-loader --upgrade
升级后无需修改配置,即可正常处理chunk对象。
方案3:临时修改第三方库代码(不推荐)
若无法升级/降级,可临时修改webpack_loader/loader.py文件的filter_chunks方法,将正则匹配的对象改为chunk的name字段:
# 原代码 ignore = any(regex.match(chunk) for regex in ignore_regexes) # 修改为 ignore = any(regex.match(chunk['name']) for regex in ignore_regexes)
该方法需修改第三方库文件,不利于后续维护,仅作为临时应急方案。
内容的提问来源于stack exchange,提问作者gggrunt
相关产品推荐
相关产品推荐

