gulp构建react项目五gulpsass处理scss

55次阅读

共计 1765 个字符,预计需要花费 5 分钟才能阅读完成。

项目结构

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

项目依赖

脚本

// 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(<Test />, 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 msg={msg}/>
  }
}

// Child
import React from 'react'

const Child = (props) => <div className="color">{props.msg}</div>

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 resolveDir = (dir) => path.resolve(__dirname, dir)

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

const clean = (done) => {del(resolveDir('./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'))
}

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

效果

正文完
 0