-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathgulpfile.js
439 lines (412 loc) · 12.2 KB
/
gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
const gulp = require('gulp');
// Pug
const pug = require('gulp-pug');
const fs = require('fs');
const data = require('gulp-data');
const path = require('path');
// HTML
const htmlhint = require('gulp-htmlhint');
const w3cjs = require('gulp-w3cjs');
const browserSyncSsi = require('browsersync-ssi');
// CSS
const sass = require('gulp-sass');
const sassGlob = require('gulp-sass-glob');
const postcss = require('gulp-postcss');
const flexBugsFixes = require('postcss-flexbugs-fixes');
const autoprefixer = require('autoprefixer');
const cleanCSS = require('gulp-clean-css');
// JS
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
const webpackConfig = require('./webpack.config');
// Image
const imagemin = require('gulp-imagemin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminPngquant = require('imagemin-pngquant');
// SVG sprite
const gulpSvgSprite = require('gulp-svg-sprite');
// Styleguide
const aigis = require('gulp-aigis');
// Utility
const cache = require('gulp-cached');
const changed = require('gulp-changed');
const browserSync = require('browser-sync');
const plumber = require('gulp-plumber');
const notify = require('gulp-notify');
const gulpif = require('gulp-if');
const del = require('del');
/**
* 開発用ディレクトリ
*/
const src = {
root: 'src/',
html: ['src/**/*.pug', '!src/**/_*.pug'],
htmlWatch: 'src/**/*.pug',
ssi: 'static/**/*.html',
data: 'src/_data/',
css: 'src/**/*.scss',
styleguideWatch: ['src/**/*.scss', 'src/**/*.md'],
js: './src/assets/js/site.js',
jsWatch: 'src/**/*.{js,vue}',
image: 'src/assets/img/**/*.{png,jpg,gif,svg}',
imageWatch: 'src/assets/img/**/*',
svgSprite: 'src/assets/svg/**/*.svg',
copy: 'static/**/*',
};
/**
* 公開用ディレクトリ
*/
const dest = {
root: 'htdocs/',
image: 'htdocs/assets/img/',
js: 'htdocs/assets/js/',
svgSprite: 'htdocs/assets/svg/',
cleanDest: 'htdocs/',
};
/**
* 環境変数を取得します。
*/
require('dotenv').config();
const environment = process.env.NODE_ENV || 'development';
const isDevelopment = environment === 'development';
const isProduction = environment === 'production';
const environmentConfig = require(`./config/${environment}.js`); // eslint-disable-line
/**
* `.pug`を`.html`にコンパイルします。
* JSONとページごとのルート相対パスの格納、ルート相対パスを使ったincludeの設定をします。
*/
function html() {
// JSONファイルの読み込み。
const locals = {
site: JSON.parse(fs.readFileSync(`${src.data}site.json`)),
};
locals.ja = {
// 日本語サイト共通のデータです。
site: JSON.parse(fs.readFileSync(`${src.data}ja/site.json`)),
};
locals.en = {
// 英語サイト共通のデータです。
site: JSON.parse(fs.readFileSync(`${src.data}en/site.json`)),
};
return (
gulp
.src(src.html)
// エラーでタスクを止めない
.pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }))
.pipe(
data(file => {
// 各ページのルート相対パスを格納します。
locals.pageAbsolutePath = `/${path
.relative(file.base, file.path.replace(/.pug$/, '.html'))
.replace(/index\.html$/, '')}`;
return locals;
}),
)
.pipe(cache('html'))
.pipe(
pug({
// `locals`に渡したデータを各Pugファイルで取得できます。
locals,
// ルート相対パスでincludeが使えるようにします。
basedir: 'src',
// Pugファイルの整形。
pretty: true,
}),
)
.pipe(gulp.dest(dest.root))
.pipe(browserSync.reload({ stream: true }))
);
}
/**
* 公開用のHTMLファイルを解析して警告やエラーを通知します。
*/
function htmlValidate() {
// 範囲を限定する場合は`products/`などと指定します。
const validateDir = '';
return gulp
.src([`${dest.root}${validateDir}**/*.html`, `!${dest.root}styleguide/**/*.html`])
.pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }))
.pipe(htmlhint('.htmlhintrc'))
.pipe(htmlhint.reporter('htmlhint-stylish'))
.pipe(
w3cjs({
// Warningも表示する
// showInfo: true,
}),
)
.pipe(
htmlhint.failOnError({
suppress: true,
}),
);
}
/**
* /static/以下のHTMLファイルを監視、更新があれば反映します。
*/
function ssi() {
return gulp.src(src.ssi).pipe(browserSync.reload({ stream: true }));
}
/**
* `.scss`を`.css`にコンパイルします。
*/
function css() {
const plugins = [
flexBugsFixes(),
autoprefixer({ grid: 'autoplace' })
];
return (
gulp
.src(src.css, {
sourcemaps: isDevelopment,
})
// globパターンでのインポート機能を追加
.pipe(sassGlob())
.pipe(
sass({
outputStyle: 'expanded',
}).on('error', sass.logError),
)
.pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }))
.pipe(postcss(plugins))
.pipe(
gulpif(
isProduction,
cleanCSS({
compatibility: {
properties: {
// 0の単位を不必要な場合は削除する
zeroUnits: false,
},
},
}),
),
)
.pipe(
gulpif(
isDevelopment,
cleanCSS({
// 圧縮せずに整形して出力する
format: 'beautify',
compatibility: {
properties: {
// 0の単位を不必要な場合は削除する
zeroUnits: false,
},
},
}),
),
)
.pipe(
gulp.dest(dest.root, {
sourcemaps: isDevelopment,
}),
)
.pipe(browserSync.reload({ stream: true }))
);
}
/**
* ES2015以降のコードをES5に変換(トランスコンパイル)します。
* Vue.jsの単一ファイルコンポーネントの変換と、ESLint・Prettierも実行します。
*/
function js() {
return gulp
.src(src.js)
.pipe(webpackStream(webpackConfig, webpack))
.pipe(gulp.dest(dest.js))
.pipe(browserSync.reload({ stream: true }));
}
/**
* 画像を圧縮します。
*/
function image() {
return gulp
.src(src.image)
.pipe(changed(dest.image))
.pipe(
plumber({
errorHandler(err) {
// eslint-disable-next-line no-console
console.log(err.messageFormatted);
this.emit('end');
},
}),
)
.pipe(
imagemin([
imageminMozjpeg({
// 画質
quality: 70,
}),
imageminPngquant({
// 画質
quality: [0.7, 0.8],
}),
imagemin.svgo({
plugins: [
// viewBox属性を削除する(widthとheight属性がある場合)。
// 表示が崩れる原因になるので削除しない。
{ removeViewBox: false },
// <metadata>を削除する。
// 追加したmetadataを削除する必要はない。
{ removeMetadata: false },
// SVGの仕様に含まれていないタグや属性、id属性やversion属性を削除する。
// 追加した要素を削除する必要はない。
{ removeUnknownsAndDefaults: false },
// コードが短くなる場合だけ<path>に変換する。
// アニメーションが動作しない可能性があるので変換しない。
{ convertShapeToPath: false },
// 重複や不要な`<g>`タグを削除する。
// アニメーションが動作しない可能性があるので変換しない。
{ collapseGroups: false },
// SVG内に<style>や<script>がなければidを削除する。
// idにアンカーが貼られていたら削除せずにid名を縮小する。
// id属性は動作の起点となることがあるため削除しない。
{ cleanupIDs: false },
],
}),
imagemin.optipng(),
imagemin.gifsicle(),
]),
)
.pipe(gulp.dest(dest.image))
.pipe(browserSync.reload({ stream: true }));
}
/**
* SVGファイルからSVGスプライトを生成します。
*/
function svgSprite() {
return gulp
.src(src.svgSprite)
.pipe(plumber({ errorHandler: notify.onError('Error: <%= error.message %>') }))
.pipe(
gulpSvgSprite({
mode: {
// SVGファイルをsymbol要素としてまとめる。
symbol: {
dest: './',
// 出力するファイル名。
sprite: 'sprite.svg',
},
},
shape: {
transform: [
{
svgo: {
plugins: [
// `style`属性を削除する。
{ removeStyleElement: true },
// `fill`属性を削除して、CSSで`fill`の変更ができるようにする。
{ removeAttrs: { attrs: 'fill' } },
],
},
},
],
},
svg: {
// xml宣言を出力する。
xmlDeclaration: false,
// DOCTYPE宣言を出力する。
doctypeDeclaration: false,
},
}),
)
.pipe(gulp.dest(dest.svgSprite))
.pipe(browserSync.reload({ stream: true }));
}
/**
* スタイルガイドを生成します。
* aigisは開発が止まっているので、別のスタイルガイドジェネレーターを検討してください。
*/
function styleguide() {
return gulp.src('./aigis/aigis_config.yml').pipe(aigis());
}
/**
* Gulpの処理を通さないディレクトリです。
* 公開用のディレクトリにコピーします。
*/
function copy() {
return gulp.src(src.copy).pipe(gulp.dest(dest.root));
}
/**
* ローカルサーバーを起動します。
*/
function serve(done) {
const httpsOption =
process.env.HTTPS_KEY !== undefined
? { key: process.env.HTTPS_KEY, cert: process.env.HTTPS_CERT }
: false;
browserSync({
server: {
// SSIを使用します。
middleware: [
browserSyncSsi({
baseDir: dest.root,
ext: '.html',
}),
],
baseDir: dest.root,
},
https: httpsOption,
// 画面を共有するときにスクロールやクリックなどをミラーリングしたくない場合はfalseにします。
ghostMode: false,
// ローカルIPアドレスでサーバーを立ち上げます。
open: 'external',
// サーバー起動時に表示するページを指定します。
startPath: '/styleguide/',
// falseに指定すると、サーバー起動時にポップアップを表示させません。
notify: false,
});
done();
}
/**
* 公開用のディレクトリを削除します。
*/
function clean() {
return del(dest.cleanDest);
}
/**
* publicなgulpタスクです。
* `gulp html`のように実行できます。
*/
exports.html = html;
exports.htmlValidate = htmlValidate;
exports.ssi = ssi;
exports.css = css;
exports.js = js;
exports.image = image;
exports.svgSprite = svgSprite;
exports.styleguide = styleguide;
exports.copy = copy;
exports.serve = serve;
exports.clean = clean;
/**
* ファイルを監視します。
*/
function watch() {
gulp.watch(src.htmlWatch, html);
gulp.watch(src.imageWatch, image);
gulp.watch(src.ssi, ssi);
gulp.watch(src.css, css);
gulp.watch(src.jsWatch, js);
gulp.watch(src.svgSprite, svgSprite);
gulp.watch(src.styleguideWatch, styleguide);
gulp.watch(src.copy, copy);
}
/**
* 開発タスクをすべて実行します。
*/
exports.build = gulp.series(
clean,
gulp.parallel(html, css, js, image, svgSprite, copy),
gulp.parallel(ssi, styleguide),
);
/**
* 開発タスクをすべて実行します。
* ローカルサーバーを起動し、リアルタイムに更新を反映させます。
*/
exports.default = gulp.series(
clean,
gulp.parallel(html, css, js, image, svgSprite, copy),
gulp.parallel(ssi, styleguide),
gulp.parallel(serve, watch),
);