【React実験】 gulpの使用

前回の記事と同じような機能をgulpで実装してみた。

  1. ディレクトリ構成
  2. それぞれのファイルの中身

ディレクトリ構成

test-gulp/
   + node_modules/
   + build/
   |  + scripts/
   |  |  + main.js
   |  |
   |  + index.html
   |
   + source/
   |  + scripts/
   |  |  + components/
   |  |  |  + app.jsx
   |  |  |  + hello.jsx
   |  |  |
   |  |  + main.js
   |  |
   |  + index.html
   |
   + package.json
   + gulpfile.js
   + .babelrc

それぞれのファイルの中身

package.json

{
  // 略
  "dependencies": {
    "gulp": "*",
    "gulp-webserver": "*",
    "gulp-plumber": "*",
    "gulp-babel": "*",
    "browserify": "*",
    "babelify": "*",
    "vinyl-source-stream": "*",
    "babel-preset-es2015": "*",
    "babel-preset-react": "*",
    "react": "*",
    "react-dom": "*"
  },
  // 略
}

gulpfile.js

var gulp = require("gulp");
var webserver = require("gulp-webserver");
var plumber = require("gulp-plumber");
var babel = require("gulp-babel");
var browserify = require("browserify");
var babelify = require("babelify");
var source = require("vinyl-source-stream");

gulp.task("build", function() {
  buildHTML();
  buildJS();
  buildCSS();
});

gulp.task("webserver", function() {
  startServer();
});

function buildHTML() {
  gulp.src("./source/**/*.html")
      .pipe(plumber())
      .pipe(gulp.dest("./build"));
}

function buildJS() {
  browserify({
    "entries": ["./source/scripts/main.js"],
    "extensions": ["", ".js", ".jsx"]
  })
      .transform(babelify)
      .bundle()
      .pipe(source("main.js"))
      .pipe(gulp.dest("./build/scripts"));
}

function buildCSS() {
  gulp.src("./source/**/*.css")
      .pipe(plumber())
      .pipe(gulp.dest("./build"));
}

function startServer() {
  gulp.src("./build")
      .pipe(webserver({
        "livereload": true
      }));
}

.babelrc

{
  "presets": [
    "es2015",
    "react"
  ]
}

source/index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Flash Cards</title>
</head>
<body>
  <div id="app"></div>

  <script src="./scripts/main.js"></script>
</body>
</html>

以下前回と同じ。

source/scripts/main.js

import App from "./components/app";

source/scripts/components/app.js

import React from "react";
import ReactDOM from "react-dom";

import Hello from "./hello";

class App extends React.Component {
  render() {
    return (
      <Hello />
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById("app")
);

source/scripts/components/hello.js

import React from "react";

export default class Hello extends React.Component {
  render() {
    return (
      <h1>Hello World!</h1>
    );
  }
}