preface

This article uses GULp to build a react development automation project to experience the fun brought by front-end engineering

To prepare

Install gulp

npm install --global gulp-cli # global install
Copy the code

Set up the basic environment

cd your-project
npm init -y or yarn init -y
npm install --save-dev gulp # Project dependencies
Copy the code

Install the basic plug-in for later use

yarn add gulp-sass fibers autoprefixer gulp-postcss gulp-html-replace gulp-rename browserify babelify vinyl-buffer gulp-uglify gulp-ejs gulp-webserver node-sass
Copy the code

Project directory

-- src
  |-- ios-switch
    |-- index.html
    |-- index.jsx
    |-- index.scss
-- gulpfile.js
-- template
  |-- index.ejs
  |-- index1.ejs
Copy the code

Compile the JSX file

function jsxCompile(path, dirname) {
  let templatePath = [];
  templatePath.push(path);
  browserifyJs({
    entries: templatePath,
    debug: true.transform: [
      babelify.configure({
        presets: ["@babel/preset-env"."@babel/preset-react"],
      }),
    ],
  })
    .bundle()
    .pipe(stream("index.js"))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(
      rename({
        dirname: dirname,
        basename: "index".extname: ".js",
      })
    )
    .pipe(gulp.dest("./dist/"));
}
Copy the code

Compiling HTML files

function htmlCompile(path, dirname) {
  gulp
    .src(path)
    .pipe(
      htmlReplace({
        css: "./index.css".js: "./index.js",
      })
    )
    .pipe(
      rename({
        dirname,
        basename: "index".extname: ".html",
      })
    )
    .pipe(gulp.dest("./dist/"));
}
Copy the code

The purpose of compiling HTML files is to replace the corresponding things

HTML file template

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title><%= name %></title>
    <script
      crossorigin
      src="https://unpkg.com/react@17/umd/react.production.min.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"
    ></script>
    <script>
      // Expose the global object
      const React = window.React;
      const ReactDOM = window.ReactDOM;
      React repackages JSX every time it is packaged, which is very slow. CDN is introduced to save packaging time
    </script>
    <! -- build:css -->
    <! -- endbuild -->
  </head>
  <body>
    <div id="app"></div>
  </body>
  <! -- build:js -->
  <! -- endbuild -->
</html>
Copy the code

Compile the SCSS file

function sassCompile(path, dirname) {
  gulp
    .src(path)
    .pipe(
      sass({ fiber: Fiber, outputStyle: "compressed" }).on(
        "error",
        sass.logError
      )
    )
    .pipe(postcss([autoprefixer()]))
    .pipe(
      rename({
        dirname,
        basename: "index".extname: ".css",
      })
    )
    .pipe(gulp.dest("./dist/"));
}
Copy the code

Listening to the

We should listen for changes in the files under the files to compile them ourselves

const watcher = watch(
  ["./src/**/*.scss"."./src/**/*.html"."./src/**/*.jsx"] and {}); watcher.on("change".function (pathL, stats) {
  console.log(`File, ${pathL} change`);
  let { pathName, dirname, extname } = getExtName(pathL);
  if (extname === ".html") {
    console.log("htmlCompile");
    htmlCompile(pathL, dirname);
  } else if (extname === ".scss") {
    console.log("sassCompile");
    sassCompile(pathL, dirname);
  } else if (extname === ".jsx") {
    console.log("jsxCompile"); jsxCompile(pathL, dirname); }});Copy the code

At the same time, we should automatically generate folder contents when creating folders, and generate routing files

watcher.on("add".function (router) {
  console.log(router, "add watcher");
  let { extname } = getExtName(router);
  if (extname === ".html") {
    const { dir } = path.parse(router);
    const res = dir.split("\ \");
    htmlCompile(router, res[1]); buildRouter(); }});const RouterWatch = watch("./src/*");
RouterWatch.on("addDir".function (router) {
  console.log(`${router} change`);
  const { name } = path.parse(router);
  gulp
    .src("./template/index1.ejs")
    .pipe(
      ejs({
        name,
      })
    )
    .pipe(
      rename({
        basename: "index".extname: ".html",
      })
    )
    .pipe(gulp.dest(router));
});

// Generate a route
function buildRouter() {
  let routers = fs.readdirSync("./src");
  routers = routers.map((router) = > {
    let template = path.join("./src", router);
    let stat = fs.lstatSync(template);
    if (stat.isDirectory()) {
      return {
        link: ". /" + router,
        fileName: "index.html".linkName: router, }; }}); routers = routers.filter((v) = >v ! = =undefined);
  return gulp
    .src("./template/index.ejs")
    .pipe(
      ejs({
        routes: routers,
      })
    )
    .pipe(
      rename({
        extname: ".html",
      })
    )
    .pipe(gulp.dest("./dist"));
}
Copy the code

Automatic start service

function server() {
  build();
  // delay 1000ms to ensure that build() is completed (errors may occur, but nothing better can be done)
  setTimeout(() = > {
    return gulp.src("./dist").pipe(
      webserver({
        port: 8001.open: true.fallback: "index.html".allowEmpty: true.livereload: {
          enable: true.filter: function (fileName) {
            if (fileName === "index.html") {
              return true;
            } else {
              return false; }},},}); },1000);
}

function build() {
  buildRouter();
  htmlCompile("./src/ios-switch/index.html"."ios-switch");
  sassCompile("./src/ios-switch/index.scss"."ios-switch");
  jsxCompile("./src/ios-switch/index.jsx"."ios-switch");
}
Copy the code

The complete code

const gulp = require("gulp");
const { watch } = gulp;
const sass = require("gulp-sass");
const Fiber = require("fibers");
const autoprefixer = require("autoprefixer");
const postcss = require("gulp-postcss");
const htmlReplace = require("gulp-html-replace");
const rename = require("gulp-rename");
const path = require("path");
const browserifyJs = require("browserify");
const babelify = require("babelify");
const stream = require("vinyl-source-stream");
const buffer = require("vinyl-buffer");
const uglify = require("gulp-uglify");
const ejs = require("gulp-ejs");
const fs = require("fs");
const webserver = require("gulp-webserver");
sass.compiler = require("node-sass");

/ / sass compilation
function sassCompile(path, dirname) {
  gulp
    .src(path)
    .pipe(
      sass({ fiber: Fiber, outputStyle: "compressed" }).on(
        "error",
        sass.logError
      )
    )
    .pipe(postcss([autoprefixer()]))
    .pipe(
      rename({
        dirname,
        basename: "index".extname: ".css",
      })
    )
    .pipe(gulp.dest("./dist/"));
}
/ / HTML compilation
function htmlCompile(path, dirname) {
  gulp
    .src(path)
    .pipe(
      htmlReplace({
        css: "./index.css".js: "./index.js",
      })
    )
    .pipe(
      rename({
        dirname,
        basename: "index".extname: ".html",
      })
    )
    .pipe(gulp.dest("./dist/"));
}
/ / JSX compilation
function jsxCompile(path, dirname) {
  let templatePath = [];
  templatePath.push(path);
  browserifyJs({
    entries: templatePath,
    debug: true.transform: [
      babelify.configure({
        presets: ["@babel/preset-env"."@babel/preset-react"],
      }),
    ],
  })
    .bundle()
    .pipe(stream("index.js"))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(
      rename({
        dirname: dirname,
        basename: "index".extname: ".js",
      })
    )
    .pipe(gulp.dest("./dist/"));
}
const watcher = watch(
  ["./src/**/*.scss"."./src/**/*.html"."./src/**/*.jsx"] and {}); watcher.on("change".function (pathL, stats) {
  console.log(`File, ${pathL} change`);
  let { pathName, dirname, extname } = getExtName(pathL);
  if (extname === ".html") {
    console.log("htmlCompile");
    htmlCompile(pathL, dirname);
  } else if (extname === ".scss") {
    console.log("sassCompile");
    sassCompile(pathL, dirname);
  } else if (extname === ".jsx") {
    console.log("jsxCompile"); jsxCompile(pathL, dirname); }}); watcher.on("add".function (router) {
  console.log(router, "add watcher");
  let { extname } = getExtName(router);
  if (extname === ".html") {
    const { dir } = path.parse(router);
    const res = dir.split("\ \");
    htmlCompile(router, res[1]); buildRouter(); }});const RouterWatch = watch("./src/*");
RouterWatch.on("addDir".function (router) {
  console.log(`${router} change`);
  const { name } = path.parse(router);
  gulp
    .src("./template/index1.ejs")
    .pipe(
      ejs({
        name,
      })
    )
    .pipe(
      rename({
        basename: "index".extname: ".html",
      })
    )
    .pipe(gulp.dest(router));
});

// Generate a route
function buildRouter() {
  let routers = fs.readdirSync("./src");
  routers = routers.map((router) = > {
    let template = path.join("./src", router);
    let stat = fs.lstatSync(template);
    if (stat.isDirectory()) {
      return {
        link: ". /" + router,
        fileName: "index.html".linkName: router, }; }}); routers = routers.filter((v) = >v ! = =undefined);
  return gulp
    .src("./template/index.ejs")
    .pipe(
      ejs({
        routes: routers,
      })
    )
    .pipe(
      rename({
        extname: ".html",
      })
    )
    .pipe(gulp.dest("./dist"));
}

function server() {
  build();
  // delay 1000ms to ensure that build() is completed (errors may occur, but nothing better can be done)
  setTimeout(() = > {
    return gulp.src("./dist").pipe(
      webserver({
        port: 8001.open: true.fallback: "index.html".allowEmpty: true.livereload: {
          enable: true.filter: function (fileName) {
            if (fileName === "index.html") {
              return true;
            } else {
              return false; }},},}); },1000);
}

function build() {
  buildRouter();
  htmlCompile("./src/ios-switch/index.html"."ios-switch");
  sassCompile("./src/ios-switch/index.scss"."ios-switch");
  jsxCompile("./src/ios-switch/index.jsx"."ios-switch");
}

function getExtName(router) {
  let pathName = path.parse(router);
  let dirname = pathName.dir.replace("src\\"."");
  let extname = pathName.ext;
  return {
    pathName,
    dirname,
    extname,
  };
}

// exports.build = build;
exports.default = server;
Copy the code

conclusion

There are still many bugs in the project. For example, gulp will directly report an error when deleting a folder, so global exception capture is not possible. I hope some big guys can help me solve them

The project address