You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Mix 如何实现源文件夹文件批量自动编译到目标文件夹

实现方案

首先在webpack.mix.js文件顶部引入Node.js内置的文件系统和路径处理模块:

const fs = require('fs');
const path = require('path');

单层目录批量编译(无嵌套子目录)

如果你的JS文件都存放在resources/js根目录下,使用以下配置即可:

// 源JS文件存放目录
const sourceDir = path.resolve(__dirname, 'resources/js');
// 编译后输出目录
const outputDir = 'public/js';

// 读取源目录下所有JS文件并批量编译
fs.readdirSync(sourceDir)
  .filter(file => file.endsWith('.js'))
  .forEach(file => {
    mix.js(path.join(sourceDir, file), outputDir);
  });

递归多层目录批量编译(保留目录结构)

如果源目录下有嵌套的子目录,需要保留结构输出到目标目录,使用以下递归逻辑:

const sourceDir = path.resolve(__dirname, 'resources/js');
const outputDir = 'public/js';

// 递归获取目录下所有JS文件
function getAllJsFiles(dir) {
  let files = [];
  const items = fs.readdirSync(dir);
  items.forEach(item => {
    const fullPath = path.join(dir, item);
    if (fs.statSync(fullPath).isDirectory()) {
      files = files.concat(getAllJsFiles(fullPath));
    } else if (item.endsWith('.js')) {
      files.push(fullPath);
    }
  });
  return files;
}

// 批量编译,保留子目录结构
getAllJsFiles(sourceDir).forEach(filePath => {
  const relativePath = path.relative(sourceDir, filePath);
  mix.js(filePath, path.join(outputDir, path.dirname(relativePath)));
});

常见问题说明

  • 通配符写法mix.js('resources/js/*.js', 'public/js')仅编译第一个文件是Laravel Mix的底层设计限制,其js方法默认不支持多入口通配符批量匹配,仅会取第一个匹配到的文件作为入口。
  • 遍历写法触发500KB报错的核心原因是源路径与输出路径配置颠倒,误将public目录下的已编译大文件作为源文件重复编译,触发了Babel的大文件编译优化警告。若修正路径后仍出现该提示,可在项目根目录新增babel.config.js添加如下配置关闭提示:
module.exports = {
  generatorOpts: {
    compact: false
  }
}

内容的提问来源于stack exchange,提问作者Huy Phạm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:39:03