gulp build报错:找不到.tmp目录下文件,gulp serve运行正常求解决方案
看起来你的问题核心是Gulp Build流程没有正确生成.tmp目录下的必要文件,而Serve模式因为实时生成这些文件所以正常,再加上Bower转Yarn后的路径变更影响了依赖注入,我们一步步来解决:
1. 先处理.tmp文件缺失的根本原因
Gulp Serve通常会启动watch任务,实时生成模板缓存和处理后的index.html,但Build流程是一次性执行的,所以你需要确保Build任务先执行生成这些文件的前置任务:
检查你的
gulpfile.js,确认build任务是否依赖了生成templateCacheHtml.js的templates任务,以及处理index.html的inject/html任务。比如:// 正确的Build任务依赖顺序 gulp.task('build', ['html', 'templates', 'styles'], function() { // 这里放最终的打包逻辑,比如压缩、移动文件到dist等 });确认模板缓存生成任务(通常用
gulp-angular-templatecache)的输出路径是.tmp,并且输入路径正确指向你的Angular模板:gulp.task('templates', function() { return gulp.src('src/client/**/*.html') // 匹配你的所有模板文件 .pipe(templatecache('templateCacheHtml.js', { module: 'yourAppModuleName', // 替换成你的Angular模块名 root: 'client' })) .pipe(gulp.dest('.tmp')); // 输出到.tmp目录 });
2. 适配Bower转Yarn后的路径变更
你把依赖从bower_components/packages迁移到了node_modules/@bower_components/packages,这会影响gulp-inject找到依赖文件,需要更新注入配置:
在处理index.html的
inject任务中,修改依赖源的路径到新的位置:gulp.task('inject', ['templates'], function() { // 指向node_modules/@bower_components下的依赖文件 var vendorJs = gulp.src([ 'node_modules/@bower_components/angular/angular.min.js', 'node_modules/@bower_components/angular-ui-router/release/angular-ui-router.min.js', // 其他你需要的依赖文件 ], {read: false}); return gulp.src('src/client/index.html') .pipe(inject(vendorJs, {name: 'inject', relative: true})) .pipe(gulp.dest('.tmp')); // 把处理后的index.html输出到.tmp,供后续build使用 });同时,确保
gulp-useref(处理index.html中<!-- build:js -->块的插件)的搜索路径包含.tmp和新的依赖目录:gulp.task('html', ['inject'], function() { return gulp.src('src/client/index.html') .pipe(useref({ searchPath: ['.tmp', 'src/client', 'node_modules/@bower_components'] })) .pipe(gulp.dest('dist')); });
3. 修复Unhandled Promise Rejection警告
这个警告是因为Gulp任务中的Promise没有错误处理,建议在任务中添加错误捕获,比如用gulp-plumber或者手动添加.catch():
gulp.task('templates', function() { return gulp.src('src/client/**/*.html') .pipe(plumber()) // 捕获任务中的错误,避免流程中断 .pipe(templatecache('templateCacheHtml.js', { module: 'yourAppModuleName', root: 'client' })) .pipe(gulp.dest('.tmp')); });
关于你的index.html是否需要修改?
目前你的index.html中的build块格式是正确的,不需要修改结构,但要确保gulp-inject和gulp-useref能正确识别这些块,配合上面的gulp任务配置即可。
内容的提问来源于stack exchange,提问作者skr07

