Gulp是一款基于Node.js构建工具(自动任务运行器)。Gulp提供了大量的集成好的插件,开发者可以通过简单的命令实现一些繁杂的功能,但是Gulp的插件也存在不少坑。
在构建完前端环境运行时,一直报语法错误:SyntaxError: Unexpected identifier,但是检查语法有没发现问题。一开始怀疑是Gulp的问题,于是编写简单的测试程序,程序如下:
var gulp = require("gulp");
gulp.task("greet",function(){
console.log("hello world");
});
结果可以看出,运行正常。
F:\Envs\front>gulp greet
[13:28:30] Using gulpfile F:\Envs\front\gulpfile.js
[13:28:30] Starting 'greet'...
hello world
[13:28:30] Finished 'greet' after 215 μs
然后又一步一步排查程序中是否存在语法错误,最终确认报错是由于gulp-cache插件的导入,其他插件一样的导入方式却只有gulp-cache插件的导入,代码如下。于是又重安装、导入gulp-cache插件,但是依旧一直出现SyntaxError: Unexpected identifier错误。
var gulp = require("gulp"),
cache = require("gulp-cache"),
cssnano = require("gulp-cssnano"),
rename = require("gulp-rename"),
uglify = require("gulp-uglify"),
concat = require("gulp-concat"),
imagemin = require("gulp-imagemin"),
bs = require("browser-sync").create();
突发奇想,会不会是插件版本的问题导致的呢?
通过npm install gulp-cache --save-dev
安装插件默认会安装最新版本的,这里我们可以看见默认安装了gulp-cache@1.1.2。
front@1.0.0 F:\Envs\front
`-- gulp-cache@1.1.2
+-- core-js@3.1.4
`-- through2@3.0.1
在此我通过npm install gulp-cache@1.1.1 --save-dev
安装gulp-cache@1.1.1,再次运行gulp,结果如下,可以看到运行成功。
F:\Envs\front>gulp
[14:09:36] Using gulpfile F:\Envs\front\gulpfile.js
[14:09:36] Starting 'bs'...
[14:09:36] Finished 'bs' after 10 ms
[14:09:36] Starting 'watch'...
[14:09:37] Finished 'watch' after 5.44 ms
[14:09:37] Starting 'default'...
[14:09:37] Finished 'default' after 11 μs
总结:gulp的插件版本很多,推荐使用之前的版本,新版本让人意想不到的坑较多。
注:本文章仅代表个人观点,若有不足敬请赐教。