如何在Django本地服务器中使用Webpack编译的生产环境文件
Django + Webpack生产环境静态资源404问题解决
场景与问题
本地开发时,使用python manage.py runserver启动Django服务,webpack-dev-server --mode=development处理前端模板,项目目录结构:
/ ├── myproj/ ├── defapp/ ├── frontend/ │ ├── dist/ │ ├── static/ │ ├── templates/ │ └── node_modules/ └── static/
执行webpack --mode=production生成frontend/dist目录后,通过manage.py runserver访问localhost时,模板无法正常加载,出现404错误:
GET https://localhost:8008/static/js/dashboard.0c3e9ffe26656a1dd3c7.bundle.js net::ERR_ABORTED 404 (Not Found)
疑问:开发阶段依赖webpack-dev-server,生产环境是否不需要Webpack服务器?
Webpack配置文件(webpack.config.js)
const path = require('path'); const { merge } = require('webpack-merge'); const BundleTracker = require('webpack-bundle-tracker'); const entries = {} for (const fileName of require('fs').readdirSync(path.resolve(__dirname, 'static', 'entries'))) { entries[fileName.split('.')[0]] = `./static/entries/${fileName}` } const baseConfig = { entry: entries, output: { filename: 'js/[name].[hash].bundle.js', path: path.resolve(__dirname, 'dist'), }, optimization: { splitChunks: { cacheGroups: { commons: { test: /[\\/]node_modules[\\/]/, chunks: 'initial', name: 'vendor', }, }, }, }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ new BundleTracker({ path: __dirname, filename: 'webpack-stats.json', }), ] }; const devConfig = merge(baseConfig, { mode: 'development', output: { publicPath: 'http://localhost:3000/static/', }, devServer: { client:{ webSocketURL: 'ws://localhost:3000/ws', }, port: 3000, hot: true, host: '0.0.0.0', allowedHosts: 'all', headers: { "Access-Control-Allow-Origin": "*" } }, }); const productConfig = merge(baseConfig, { mode: 'production', output: { publicPath: '/static/' } }) module.exports = (env, options) => { return options.mode === 'production' ? productConfig : devConfig }
解决方案
1. 修改Django配置文件
在项目的settings.py中添加静态文件目录配置:
STATICFILES_DIRS = ( os.path.join(BASE_DIR,'frontend/dist'), )
2. 收集静态资源
执行Django静态资源收集命令:
python manage.py collectstatic
补充说明
开发阶段webpack-dev-server将打包后的资源存放在内存中,通过publicPath指定的地址提供访问;生产环境下Webpack仅负责将编译后的资源输出到frontend/dist目录,需要让Django识别这个目录作为静态资源来源,再通过collectstatic将所有静态资源统一收集到Django配置的STATIC_ROOT目录(默认项目根目录下的/static/),这样就能正确加载静态资源了。生产环境确实不需要运行webpack-dev-server。
内容的提问来源于stack exchange,提问作者whitebear
相关产品推荐
相关产品推荐

