【发布时间】:2017-07-25 11:32:49
【问题描述】:
我正在开发一个使用 Node.js、Express 和 Gulp 构建静态网站的小应用程序(玩弄以提升我的技能)。 该应用程序由用于构建 HTML 的 PUG 模板引擎和一个 Asset 文件夹组成,我的所有静态文件(图像、css、js)都存放在该文件夹中。
images 文件夹有很多初始图像,我们不一定要使用所有图像。 但是,我想做的是;
- 能够读取html文件(index.html)
- 检索图像的路径
- 从资产目录中获取正在使用的图片
- 复制图像并在目标文件夹中创建另一个结构 index.html 和图片
- 如果可能,压缩网站的最终输出文件夹。
下面是应用的结构。
|- Battlefield
|- app
|- Assets
|- images
|- Views
|- html
|- index.html
|- pug
|- index.pug
|- dest
这是我的 Gulpfile.js
// Requiring Gulp
var gulp = require('gulp');
var sass = require('gulp-sass');
var pug = require('gulp-pug');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');
gulp.task('hello', function() {
//Test Gulp task 'hello'
console.log('Hello Zell');
});
gulp.task('sass', function() {
return gulp.src('app/Assets/scss/**/*.scss') // Gets all files ending with .scss in app/scss and children dirs
.pipe(sass()) //using gulp-sass
.pipe(gulp.dest('app/Assets/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('pug', /*['copy'],*/ function() {
return gulp.src('app/Views/pug/**/*.pug')
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('app/Views/html'))
.pipe(browserSync.reload({
stream: true
}))
});
// Multiple watch process
gulp.task('watch', ['browserSync', 'sass', 'pug'], function() {
gulp.watch('app/Assets/scss/**/*.scss', ['sass']);
gulp.watch('app/Views/pug/**/*.pug', ['pug']);
// Reloads the browser whenever HTML or CSS or JS files change
gulp.watch('app/Views/html/*.html', browserSync.reload);
gulp.watch('app/Assets/css/**/*.css', browserSync.reload);
gulp.watch('app/Assets/js/**/*.js', browserSync.reload);
});
gulp.task('browserSync', ['nodemon'], function() {
browserSync.init(null, {
proxy: "http://localhost:4000",
files: ["app/**/*.*"],
port: 7000,
});
});
gulp.task('nodemon', function(cb) {
var started = false;
return nodemon({
script: 'server.js'
}).on('start', function() {
// to avoid nodemon being started multiple times
// thanks github user @matthisk
if (!started) {
cb();
started = true;
}
});
});
更新:
下面是package.json:
{
"name": "Framework",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Aumeeruddy Ajmal",
"license": "ISC",
"devDependencies": {
"browser-sync": "^2.18.8",
"gulp": "^3.9.1",
"gulp-pug": "^3.3.0",
"gulp-sass": "^3.1.0",
"express": "^4.15.3",
"body-parser": "^1.17.2",
"cookie-parser": "^1.4.3",
"multer": "^1.3.0",
"gulp-nodemon": "^2.2.1"
}
}
例如,我有以下 HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Static files</title>
</head>
<body>
<img src="images/logo.jpg" alt="">
<img src="images/main.jpg" alt="">
<img src="images/example.jpg" alt="">
</body>
</html>
我希望节点或 gulp 通过命令或任务能够读取该 html,找到 <img src="..." alt=""> 部分,检索图像的路径。
查看路径目录并将图像复制到另一个目录(用于重组),然后压缩输出包。
【问题讨论】:
-
"要能够读取html文件(index.html)"什么意思?当 browserSync 启动时 index.html 首先查看?对吗?
-
嗨@HaHuuTin,感谢您的回复。我更新了问题以更准确。我希望你能得到这张照片。如果您需要更多信息,请告诉我。谢谢,阿杰马尔