Rails 6.1.4搭配Webpacker 5.1.1开发环境编译JS/CSS速度极慢如何解决?
问题修复方案
请按以下步骤逐一排查修复:
1. 修正不兼容依赖
你项目的package.json存在2个明确的版本冲突依赖,是导致全量编译的核心原因:
extract-text-webpack-plugin@3.0.2是Webpack 3配套的CSS提取插件,和Webpacker 5依赖的Webpack 4完全不兼容,直接执行yarn remove extract-text-webpack-plugin卸载即可,Webpacker 5已内置mini-css-extract-plugin处理CSS提取逻辑,无需额外安装该插件webpack-cli@4.9.1和Webpacker 5依赖的Webpack 4版本不兼容,执行yarn remove webpack-cli卸载,Webpacker自带的编译命令不需要额外安装webpack-cli
2. 开启编译缓存配置
修改config/webpacker.yml开发环境配置项:
development: <<: *default compile: true # 开启文件系统缓存 cache: true # 用轻量化的source map提升编译速度 source_map: cheap-module-source-map dev_server: hmr: true inline: true
3. 新增编译加速插件与loader配置
修改config/webpack/development.js,添加以下配置:
const { environment } = require('@rails/webpacker') // 开启babel-loader编译缓存 const babelLoader = environment.loaders.get('babel') babelLoader.use.find(item => item.loader === 'babel-loader').options.cacheDirectory = true // 启用hard-source-webpack-plugin模块缓存 const HardSourceWebpackPlugin = require('hard-source-webpack-plugin') environment.plugins.prepend('HardSource', new HardSourceWebpackPlugin()) module.exports = environment
4. 调整服务启动顺序
使用dev-server热重载时,必须按以下顺序启动:
- 先执行
./bin/webpack-dev-server,确认服务启动无报错 - 再启动Rails服务,此时Rails会自动对接dev-server的增量编译能力,不会触发全量编译
完成以上配置后,首次编译速度会提升30%左右,首次编译完成后的增量修改编译耗时可降低到10秒以内。
内容的提问来源于stack exchange,提问作者Manivannan Jeganathan
相关产品推荐
相关产品推荐

