Gulp 的使用
官网:https://gulpjs.com/docs/en/getting-started/quick-start
可以使用 Gulp 直接来构建自动化,使用简单,里面提供了 4000 多个插件
// gulpfile.js
const gulp = require('gulp');
const clean = require('gulp-clean'); // https://www.npmjs.com/package/gulp-clean
const concat = require('gulp-concat'); // https://www.npmjs.com/package/gulp-concat
const inject = require('gulp-inject'); // https://www.npmjs.com/package/gulp-inject
const uglify = require('gulp-uglify'); // https://github.com/terinjokes/gulp-uglify
const sourcemaps = require('gulp-sourcemaps'); // https://www.npmjs.com/package/gulp-sourcemaps
const spawn = require('cross-spawn'); // https://www.npmjs.com/package/cross-spawn
const postcss = require('gulp-postcss'); // https://github.com/postcss/gulp-postcss
const babel = require('gulp-babel'); // https://github.com/babel/gulp-babel
// 安装
// pnpm i -D gulp-babel @babel/core @babel/preset-env cross-spawn gulp gulp-clean gulp-concat gulp-inject gulp-postcss gulp-sourcemaps gulp-uglify
// NOTE: 需要去 package.json 中配置 "scripts": { "build:vite": "vite build" } 并且删除 "type": "module" 或改为 "type": "commonjs"
const pathDist = 'dist';
gulp.task('clean', (cb) => {
gulp.src([pathDist], { read: false, allowEmpty: true }).pipe(clean());
console.log('清空dist目录成功');
cb();
});
gulp.task('build-vite', (cb) => {
spawn.sync('pnpm run build:vite', [], { stdio: 'inherit' });
console.log('编译vite项目成功');
cb();
});
gulp.task('build-css', (cb) => {
gulp.src(`${pathDist}/**/*.css`)
.pipe(postcss([]))
.pipe(gulp.dest(`${pathDist}/styles`));
console.log('编译styles成功');
cb();
});
gulp.task('build-js', (cb) => {
gulp.src(`${pathDist}/**/*.js`)
.pipe(sourcemaps.init())
.pipe(
babel({
presets: ['@babel/env'],
compact: true,
}),
)
.pipe(concat(`sitecore-console.min.js`))
.pipe(uglify())
.pipe(sourcemaps.write(`maps`))
.pipe(gulp.dest(`${pathDist}/scripts`));
console.log('编译js成功');
cb();
});
gulp.task('build-inject', (cb) => {
gulp.src(`${pathDist}/index.html`)
.pipe(inject(gulp.src('./src/**/*.js', { read: false })))
.pipe(gulp.dest(pathDist));
console.log('编译inject成功');
cb();
});
gulp.task('default', gulp.series(['clean', 'build-vite', 'build-css', 'build-js']), (cb) => {
console.log('编译成功');
cb();
});