gulp构建react项目六:gulp-cheerio将打包后的js、css引入到html

项目结构

gulp
├── src
│   ├── components
│   │   ├── Test
│   │   |   └── index.jsx
│   │   ├── Child
│   │   |   ├── index.css
│   │   |   └── index.jsx
│       └── App.jsx 
├── node_modules
├── index.js
├── gulpfile.js
├── index.html
└── package.json

依赖
image.png
脚本

// index.js
import './src/App.jsx'

// App.jsx
import React from 'react'
import { render } from 'react-dom'
import Test from './components/Test/index.jsx'

render(, document.getElementById("app"))

// Test
import React from 'react'
import Child from '../Child/index.jsx'

export default class Test extends React.Component {
  state = {
    msg: 'hello, world'
  }

  render() {
    const { msg } = this.state
    return 
  }
}

// Child
import React from 'react'

const Child = (props) => 
{props.msg}
export default Child

scss

.color {
  color: red;
}

构建脚本

const path = require('path')
const gulp = require('gulp')
const babelify = require('babelify')
const browserify = require('browserify')
    // 转成stream流,gulp系
const source = require('vinyl-source-stream')
    // 转成二进制流,gulp系
const buffer = require('vinyl-buffer')
const { series, parallel } = require('gulp')
const del = require('del')
const concat = require('gulp-concat')
const sass = require('gulp-sass')
const cheerio = require('gulp-cheerio')


const resolveDir = (dir) => path.resolve(__dirname, dir)

const _path = {
  main_js: resolveDir('./index.js'),
  scss: ['./src/components/**/*.scss'],
  html: resolveDir('./index.html')
}

const clean = (done) => {
  del('./dist')
  done()
}

const _css = () => {
  return gulp.src(_path.scss)
    .pipe(sass())
    .pipe(concat('app.css'))
    .pipe(gulp.dest('./dist/css'))
}

const _script = () => {
  return browserify({
      entries: _path.main_js,
      transform: [babelify.configure({
        presets: ['@babel/preset-env', '@babel/preset-react'],
        plugins: [
          '@babel/plugin-transform-runtime', 
          ["@babel/plugin-proposal-decorators", { "legacy": true }], 
          ["@babel/plugin-proposal-class-properties", { "loose": true }]
        ]
      })]
    })
    .bundle()
    .pipe(source('app.js'))
    // .pipe(buffer())
    .pipe(gulp.dest('./dist/js'))
}

const _html = () => {
  return gulp.src(_path.html)
  .pipe(cheerio(($ => {
    $('script').remove()
    $('link').remove()
    $('body').append('')
    $('head').append('')
  })))
  .pipe(gulp.dest('./dist'))
}


module.exports.build = series(clean, parallel(_script, _css, _html))

效果
image.png

你可能感兴趣的:(gulp)