import gulp from "gulp";
import gulpIf from "gulp-if";
import MemoryFS from "memory-fs";
import syncBrowser from "browser-sync";
const browserSync = syncBrowser.create();
const __dirname = process.cwd();
// 创建内存文件系统实例
const mfs = new MemoryFS();
import htmlmin from "gulp-htmlmin"; // 压缩html文件
import uglify from "gulp-uglify"; // 压缩js文件
import babel from "gulp-babel"; // ES6转ES5
import sass from "gulp-sass"; // sass编译
import cleanCss from "gulp-clean-css"; // 压缩css文件
import replace from "gulp-replace"; // 替换文件内容
import ignore from "gulp-ignore"; // 排除文件不进入打包结果
import { deleteAsync } from "del"; // 清除打包目标目录
import fs from "fs/promises";
import path from "path";
import map from "map-stream";
import { createProxyMiddleware } from "http-proxy-middleware";
const devAssetsDir = "src";
const htmlGlob = `${devAssetsDir}/**/*.html`;
const cssGlob = `${devAssetsDir}/**/*.css`;
const jsGlob = `${devAssetsDir}/**/*.js`;
const staticGlob = `${devAssetsDir}/static/**/*`;
const modulesGlob = "modules/**/*";
const allFileGlob = `${devAssetsDir}/**/*`;
/**
* @type {"dev" | "prod"} 环境变量
*/
let env = "dev";
function setEnv(currEnv) {
return async () => {
env = currEnv;
};
}
import config from "./config.js";
let { moduleMap, assetsDir, devServer } = config;
let { browsersync: browsersyncOptions, httpProxy } = devServer && typeof devServer === "object" ? devServer : {};
moduleMap = parseModuleMap(moduleMap);
// 异步读取文件内容
async function getCode(path) {
return await fs.readFile(path, "utf8");
}
// 清除dist目录的任务
async function cleanTask() {
return deleteAsync([assetsDir]); // 使用 del 删除 dist 目录及其内容
}
export const clean = cleanTask;
/**
* @description 注入模块
* @param {NodeJS.ReadWriteStream} ctx
* @returns {NodeJS.ReadWriteStream}
*/
async function injectModules(ctx) {
// 遍历模块文件,将每个模块文件的内容替换到对应的模块标签中
for (const key in moduleMap) {
const filePath = path.join(__dirname, moduleMap[key]);
const code = await getCode(filePath);
const replaceStream = replace(key, code);
ctx = ctx.pipe(replaceStream);
}
return ctx;
}
// 制定html任务
async function htmlTask() {
const condition = env === "prod";
let ctx = gulp.src(htmlGlob, {
ignore: [staticGlob],
});
ctx = await injectModules(ctx);
return (
ctx
.pipe(
htmlmin({
removeComments: condition, // 生产环境下移除注释
collapseWhitespace: condition, // //压缩HTML
collapseBooleanAttributes: condition, //省略布尔属性的值 ==>
removeEmptyAttributes: env === "prod", //删除所有空格作属性值 ==>
removeScriptTypeAttributes: false, //删除