1. miwashutaro0611

    No comment

    miwashutaro0611
Changes in body
Source | HTML | Preview
@@ -104,10 +104,129 @@
watch(filesrc.css, css)
}
exports.build = parallel(html, css)
```
+# ブラウザが開く&開発・本番環境などで行うことを切り分ける(2019.06.16追記)
+
+## 変更した点
+
+- `scss`から`stylus`に変更
+- `browser-sync`を使いgulpfile起動時にブラウザを開く
+- 実際のプロジェクトで使ったものの抜粋なので、`pug`の対応ファイルの場所の変更
+- 開発時にはcssのsourcemap生成・本番時にはhtmlファイルを1行にするなどの開発・本番環境で処理を分ける
+
+## ファイルの中身
+
+```js:gulpfile.js
+const { src, dest, watch, parallel } = require('gulp')
+const pug = require('gulp-pug')
+const data = require('gulp-data')
+const stylus = require('gulp-stylus')
+const postcss = require('gulp-postcss')
+const cssnext = require('postcss-cssnext')
+const plumber = require('gulp-plumber')
+const notify = require('gulp-notify')
+const sourcemaps = require('gulp-sourcemaps')
+const cleanCSS = require('gulp-clean-css')
+const browserSync = require('browser-sync')
+const htmlmin = require('gulp-htmlmin')
+const mode = require('gulp-mode')({
+ modes: ['production', 'development'],
+ default: 'development',
+ verbose: false,
+})
+
+
+const srcPath = {
+ html: [
+ 'src/pages/**/*.pug',
+ '!' + 'src/**/_*.pug',
+ ],
+ stylus: 'src/**/*.styl',
+}
+
+const destPath = {
+ root: 'dist/',
+ assets: 'dist/assets/',
+}
+
+const htmlFunc = () => {
+ return src(srcPath.html)
+ .pipe(
+ plumber({ errorHandler: notify.onError('Error: <%= error.message %>') })
+ )
+ .pipe(
+ data(file => {
+ return {
+ relativePath: file.history[0].replace(file.base, ''),
+ }
+ })
+ )
+ .pipe(
+ pug({
+ basedir: 'src',
+ pretty: true,
+ })
+ )
+ .pipe(
+ mode.production(
+ htmlmin({
+ collapseWhitespace: true,
+ minifyJS: true,
+ removeComments: true,
+ })
+ )
+ )
+ .pipe(dest(destPath.root))
+ .pipe(browserSync.reload({ stream: true }))
+}
+
+const browsers = [
+ 'last 2 versions',
+ '> 5%',
+ 'ie = 11',
+ 'not ie <= 10',
+ 'ios >= 8',
+ 'and_chr >= 5',
+ 'Android >= 5',
+]
+
+const stylusFunc = () => {
+ return src('src/assets/stylus/*.styl')
+ .pipe(mode.development(sourcemaps.init()))
+ .pipe(
+ plumber({ errorHandler: notify.onError('Error: <%= error.message %>') })
+ )
+ .pipe(stylus())
+ .pipe(postcss([cssnext(browsers)]))
+ .pipe(cleanCSS())
+ .pipe(mode.development(sourcemaps.write()))
+ .pipe(dest(`${destPath.assets}css/`))
+ .pipe(browserSync.reload({ stream: true }))
+}
+
+const browserSyncFunc = () => {
+ browserSync({
+ server: {
+ baseDir: 'dist/',
+ index: 'index.html',
+ },
+ })
+}
+
+const watchFiles = () => {
+ watch(srcPath.html[0], htmlFunc)
+ watch(srcPath.stylus, stylusFunc)
+}
+
+exports.default = parallel(watchFiles, browserSyncFunc)
+
+exports.build = parallel(htmlFunc, stylusFunc)
+
+```
+
# 参考にしたリンク
- https://twitter.com/tonkotsuboy_com/status/1133319513825394688
- https://gulpjs.com/docs/en/getting-started/working-with-files
- https://gulpjs.com/docs/en/getting-started/watching-files