是否能够从UI页面运行gulp任务?
例如:拥有一个Web表单或任何类型的输入,当您点击任何按钮时,运行一个已定义和特定的任务(运行构建、编译SASS等)。
谢谢
是否能够从UI页面运行gulp任务?
例如:拥有一个Web表单或任何类型的输入,当您点击任何按钮时,运行一个已定义和特定的任务(运行构建、编译SASS等)。
谢谢
是的,你可以。只需要在需要时执行 gulp 任务名称
即可。你需要向一个执行 gulp 命令的脚本发送 ajax 请求。例如,你可以使用 nodejs 和 express 来制作一个工作示例:
gulpfile
gulp.task('minify' , function(){
console.log('gulp called!');
gulp.src('scripts/src/test.js')
.pipe(minify() )
.pipe(gulp.dest('scripts/bin/'));
});
server.js
var express = require('express')
var app = express();
var exec = require('child_process').exec;
app.use(express.static('public'))
app.post('/send' , function(req , res){
console.log('this was called');
exec('gulp minify');
res.send('success!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
public/index.html
<html>
<head>
</head>
<body>
<button onclick=send()>Execute gulp minify</button>
</body>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script>
function send(){
$.ajax({
url : 'http://localhost:3000/send',
method : 'POST',
success : function(res){
console.log(res);
},
error : function(response){
console.log('Error!');
console.log(response);
}
});
}
</script>
</html>
package.json
{
"name": "gulp-from-script",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.0",
"gulp-uglify": "^2.0.0"
}
}
scripts/src/test.js
function test(){
console.log('this file should be minified to bin/test.js on click');
//end.
}
npm install
然后启动服务:
node server.js
然后前往:
localhost:3000/index.html
点击按钮后,一个压缩文件应该会出现在 /scripts/bin/test.js
下。console.log('gulp called!');
会在浏览器控制台中显示吗? - Kumaresan Sd答案:我不知道,但如果是这样的话,你就不应该这么做。
为什么?:Gulp 旨在成为开发过程中的任务运行器,由 shell(终端/命令行)运行和控制,而不是在 Web/浏览器端运行。
你可以使用 Gulp 来与 React 配合使用。Web 行为由 React 处理。你可以很容易地学习 React,有很多文档和教程。我喜欢 this one。