關於 Gulp V3 的環境配置,請參考如下文章:
使用Gulp(V3.+) + Babel + Browserify 配置ES6的開發環境
如果使用的 Gulp 版本是 V4 以上的,配置相對於 V3 有些許的變化。
1.注意點
往往我們使用的 Gulp 編譯命令是使用的全局的 Gulp,而非局部的。所以,如果局部使用了 V4的版本,而全局的Gulp 是 V3 版本的,那麼在執行 gulp 命令時,會出現以如下錯誤信息:
C:\Users\X_XXXXX\xxx\Roaming\npm\node_modules\gulp\bin\gulp.js:129
gulpInst.start.apply(gulpInst, toRun);
^
TypeError: Cannot read property 'apply' of undefined
at C:\Users\X_XXXXX\xxx\Roaming\npm\node_modules\gulp\bin\gulp.js:129:20
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
at Function.Module.runMain (module.js:695:11)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
可以先使用如下命令查看一下全局的 gulp 版本信息:
1.1 解決方式有 2 個
1.1.1 將全局的 gulp 更新到V4
使用如下命令更新 gulp 的版本信息
npm install -g gulp
成功之後,再使用命令查看其版本,如果版本也在 V4 及以上就可以了。
1.1.2 使用局部的 gulp 運行編譯命令
在如下路徑中執行 gulp 命令:
~gulp_v4_babel\node_modules\gulp\node_modules\.bin>gulp
這樣就是使用的局部的 gulp 來進行編譯的了。
2. 項目結構
3. 測試代碼
3.1 App.js
class App {
constructor(name){
this.name = name;
}
render() {
document.querySelector("#app").innerHTML = "gulp-babel " + this.name;
}
}
export default App;
3.2 entry.js
import App from "./App";
(function () {
let app = new App(" asdf");
app.render();
})();
3.3 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app"></div>
<script src="./dist/js/app.min.js"></script>
</body>
</html>
3. package.json
{
"name": "gulp_v4_babel",
"version": "1.0.0",
"description": "",
"main": "entry.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.8.3",
"@babel/preset-env": "^7.8.3",
"@babel/runtime": "^7.8.3",
"babel-loader": "^8.0.6",
"babelify": "^10.0.0",
"browserify": "^16.5.0",
"gulp": "^4.0.2",
"gulp-babel": "^8.0.0",
"gulp-concat": "^2.6.1",
"gulp-rev": "^9.0.0",
"gulp-series": "^1.0.2",
"gulp-uglify": "^3.0.2",
"gulp-watch": "^5.0.1",
"vinyl-source-stream": "^2.0.0"
}
}
4. .babelrc babel基本配置
{
"presets": ["@babel/preset-env"]
}
5. gulpfile.js
const gulp = require("gulp"),
babel = require("gulp-babel"),
uglify = require("gulp-uglify"),
concat = require("gulp-concat"),
browserify = require("browserify"),
source = require("vinyl-source-stream");
gulp.task("js", function () {
return gulp.src("./src/js/*.js")
.pipe(babel())
.pipe(uglify())
.pipe(gulp.dest("build/js"));
});
gulp.task("browserify", gulp.series(["js"], function () {
var b = browserify({
entries: "./build/js/entry.js"
});
return b.bundle()
.pipe(source("app.min.js"))
.pipe(gulp.dest("./dist/js"));
}));
gulp.task("default", gulp.series(["browserify"]));
當然這裏也可以使用 gulp 的 transform 方法,而不使用 gulp-babel 單獨再編譯。具體可參考
使用Gulp(V3.+) + Babel + Browserify 配置ES6的開發環境