项目结构
gulp01
├── src
│ ├── components
│ │ ├── Test
│ │ | └── index.jsx
│ │ ├── Child
│ │ | ├── index.css
│ │ | └── 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
css
.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 resolveDir = (dir) => path.resolve(__dirname, dir)
const _path = {main_js: resolveDir('./index.js'),
css: ['./src/components/**/*.css']
}
const clean = (done) => {del(resolveDir('./dist'))
done()}
const _css = () => {return gulp.src(_path.css)
.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))
在 index.html 中引入打包之后的 js 和 css
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./css/app.css">
</head>
<body>
<div id="app"></div>
<script src="./js/app.js"></script>
</body>
</html>
效果: