tachybase_todo/packages/core/build/src/babel.ts
jack zhang 5df3b0e75d
refactor!: plugins build and plugins load (#2253)
* refactor: plugin build and plugin template

* refactor: plugins' deps

* refactor: plugins bugs

* feat: add plugin static middleware

* fix: bugs

* refactor: frontend plugin add from remote

* refactor: delete useless app/client/plugins

* fix: requirejs move to local

* fix: tests case

* refactor: add src/client and src/server dir check

* fix: lodash tree shaking

* refactor: add BUILD_TIP

* refactor: add file size tip

* fix: bugs

* fix: bug

* fix: change china-division

* fix: change plugins response

* fix: recover dynamicImport

* fix: change server src entry

* fix: test error

* fix: plugins sourcemap => false

* fix: production file error

* refactor: change build tools to vite and tsup

* fix: yarn.lock

* fix: bugs

* fix: server build bugs

* fix: delete .fatherrc.ts

* fix: bug

* fix: bug

* fix: bugs

* fix: bugs

* fix: bugs

* refactor: add plugin d.ts

* refactor: delete fatherrc

* refactor: delete father scripts

* refactor: build bug

* fix: bug

* fix: deps adjust

* fix: add build tips

* fix: bug

* refactor: ignore plugins when build client

* docs: update doc

* refactor: docs and build

* fix: bug

* refactor: build deps

* fix: add USER_REMOTE_PLUGIN env

* feat: add plugin static cache

* feat: add build deps cache

* fix: bugs

* test: add test

* fix: add plugin depden on plugin tip

* fix: adjust shouldDevDependencies

* fix: deps

* fix: ajust deps

* fix: mobile style error

* fix: map error

* fix: test

* fix: bug

* feat: lodash and dayjs import from themself

* feat: @emotion/css 、ahooks and lodash to global

* fix: theme-editor plugin error

* fix: review

* feat: move all plugins' dependencies to devDependencies

* feat: change build

* feat: add devPlugins

* fix: bug

* fix: bugs

* fix: bugs

* fix: bugs

* feat: build bugs

* fix: bugs

* fix: bugs

* fix: review

* fix: bug

* fix: change deps build

* fix: bugs

* fix: bug

* fix: bug

* fix: bugs

* fix: bug

* fix: bug

* fix: multi language

* fix: dist

* fix: cronstrue

* fix: getPackageClientStaticUrl

* fix: antd dayjs locale

* fix: plugin' d.ts import from dist

* fix: multi language

* fix: build types error

* fix: requireModule

* fix: plugin lifecycle

* fix: client resource

* fix: improve code

* fix: locale

* feat: custom build

* fix: require locale

* fix: improve code

* fix: improve code

* fix: skip preset

* fix: collection undefined

* feat: yarn build

* fix: remove enabled

* fix: update dockerfile

* fix: formily version

* docs: update v12 changelog

* fix: devDependencies

* feat: @nocobase/app

* feat: generateAppDir

* fix: improve code

* fix: 0.11.1-alpha.5

* fix: missing @nocobase/client

* fix: error

* fix: add .npmignore

* feat: upgrade antd version

* fix: dependencies

* fix: peerDependencies

* fix: remove china-division dep

* fix: toposort deps

* fix: update dockerfile

* fix: plugin template

* fix: app client outputPath

* feat: update docs

* fix: nginx server root

* fix: storage/.app-dev

* fix: getChinaDivisionData

* feat: plugin info

* feat: update docs

* fix: docs menu

---------

Co-authored-by: chenos <chenlinxh@gmail.com>
2023-08-02 00:07:52 +08:00

273 lines
7.5 KiB
TypeScript
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { join, extname, relative } from "path";
import { existsSync, readFileSync, statSync } from "fs";
import vfs from "vinyl-fs";
import signale from "signale";
import lodash from "lodash";
import rimraf from "rimraf";
import through from "through2";
import slash from "slash2";
import * as chokidar from "chokidar";
import * as babel from "@babel/core";
import gulpTs from "gulp-typescript";
import gulpLess from "gulp-less";
import gulpPlumber from "gulp-plumber";
import gulpIf from "gulp-if";
import chalk from "chalk";
import fs from 'fs-extra'
import getBabelConfig from "./getBabelConfig";
import { Dispose, IBundleOptions } from "./types";
import * as ts from "typescript";
interface IBabelOpts {
cwd: string;
rootPath?: string;
type: "esm" | "cjs";
target?: "browser" | "node";
log?: (string) => void;
watch?: boolean;
dispose?: Dispose[];
isPlugin?: boolean;
importLibToEs?: boolean;
bundleOpts: IBundleOptions;
}
interface ITransformOpts {
file: {
contents: string;
path: string;
};
type: "esm" | "cjs";
}
export default async function (opts: IBabelOpts) {
const {
cwd,
rootPath,
type,
watch,
dispose,
importLibToEs,
log,
isPlugin = false,
bundleOpts: {
target = "browser",
runtimeHelpers,
extraBabelPresets = [],
extraBabelPlugins = [],
browserFiles = [],
nodeFiles = [],
nodeVersion,
disableTypeCheck,
cjs,
lessInBabelMode,
},
} = opts;
const srcPath = join(cwd, "src");
const targetDir = type === "esm" ? "es" : isPlugin ? 'dist' : "lib";
const targetPath = join(cwd, targetDir);
if (!isPlugin) {
log(chalk.gray(`Clean ${targetDir} directory`));
rimraf.sync(targetPath);
} else {
if (fs.existsSync(targetPath)) {
// exclude node_modules
const files = fs.readdirSync(targetPath, { recursive: false }) as string[];
files.forEach((file) => {
if (file !== 'node_modules') {
rimraf.sync(join(targetPath, file));
}
})
}
}
function transform(opts: ITransformOpts) {
const { file, type } = opts;
const { opts: babelOpts, isBrowser } = getBabelConfig({
target,
type,
typescript: true,
runtimeHelpers,
filePath: slash(relative(cwd, file.path)),
browserFiles,
nodeFiles,
nodeVersion,
lazy: cjs && cjs.lazy,
lessInBabelMode,
});
if (importLibToEs && type === "esm") {
babelOpts.plugins.push(require.resolve("../lib/importLibToEs"));
}
babelOpts.presets.push(...extraBabelPresets);
babelOpts.plugins.push(...extraBabelPlugins);
const relFile = slash(file.path).replace(`${cwd}/`, "");
log(
`Transform to ${type} for ${chalk[isBrowser ? "yellow" : "blue"](
relFile
)}`
);
return babel.transform(file.contents, {
...babelOpts,
filename: file.path,
// 不读取外部的babel.config.js配置文件全采用babelOpts中的babel配置来构建
configFile: false,
}).code;
}
/**
* tsconfig.json is not valid json file
* https://github.com/Microsoft/TypeScript/issues/20384
*/
function parseTsconfig(path: string) {
const readFile = (path: string) => readFileSync(path, "utf-8");
const result = ts.readConfigFile(path, readFile);
if (result.error) {
return;
}
const pkgTsConfig = result.config;
if (pkgTsConfig.extends) {
const rootTsConfigPath = slash(relative(cwd, pkgTsConfig.extends));
const rootTsConfig = parseTsconfig(rootTsConfigPath);
if (rootTsConfig) {
const mergedConfig = {
...rootTsConfig,
...pkgTsConfig,
compilerOptions: {
...rootTsConfig.compilerOptions,
...pkgTsConfig.compilerOptions,
},
};
return mergedConfig;
}
}
return pkgTsConfig;
}
function getTsconfigCompilerOptions(path: string) {
const config = parseTsconfig(path);
return config ? config.compilerOptions : undefined;
}
function getTSConfig() {
const tsconfigPath = join(cwd, "tsconfig.json");
const templateTsconfigPath = join(__dirname, "../template/tsconfig.json");
if (existsSync(tsconfigPath)) {
return getTsconfigCompilerOptions(tsconfigPath) || {};
}
if (rootPath && existsSync(join(rootPath, "tsconfig.json"))) {
return getTsconfigCompilerOptions(join(rootPath, "tsconfig.json")) || {};
}
return getTsconfigCompilerOptions(templateTsconfigPath) || {};
}
function createStream(src) {
const tsConfig = getTSConfig();
const babelTransformRegexp = disableTypeCheck ? /\.(t|j)sx?$/ : /\.jsx?$/;
function isTsFile(path) {
return /\.tsx?$/.test(path) && !path.endsWith(".d.ts");
}
function isTransform(path) {
if (isPlugin) return false
return babelTransformRegexp.test(path) && !path.endsWith(".d.ts");
}
return vfs
.src(src, {
allowEmpty: true,
base: srcPath,
})
.pipe(watch ? gulpPlumber() : through.obj())
.pipe(
gulpIf((f) => !disableTypeCheck && isTsFile(f.path), gulpTs(tsConfig))
)
.pipe(
gulpIf(
(f) => lessInBabelMode && /\.less$/.test(f.path),
gulpLess(lessInBabelMode || {})
)
)
.pipe(
gulpIf(
(f) => isTransform(f.path),
through.obj((file, env, cb) => {
try {
file.contents = Buffer.from(
transform({
file,
type,
})
);
// .jsx -> .js
file.path = file.path.replace(extname(file.path), ".js");
cb(null, file);
} catch (e) {
signale.error(`Compiled faild: ${file.path}`);
console.log(e);
cb(null);
}
})
)
)
.pipe(vfs.dest(targetPath))
}
return new Promise((resolve) => {
const patterns = [
isPlugin ? join(srcPath, "**/*.{ts,tsx}") : join(srcPath, "**/*"),
`!${join(srcPath, "**/fixtures{,/**}")}`,
`!${join(srcPath, "**/demos{,/**}")}`,
`!${join(srcPath, "**/__test__{,/**}")}`,
`!${join(srcPath, "**/__tests__{,/**}")}`,
`!${join(srcPath, "**/*.mdx")}`,
`!${join(srcPath, "**/*.md")}`,
`!${join(srcPath, "**/*.+(test|e2e|spec).+(js|jsx|ts|tsx)")}`,
`!${join(srcPath, "**/tsconfig{,.*}.json")}`,
`!${join(srcPath, ".umi{,-production,-test}{,/**}")}`,
];
createStream(patterns).on("end", () => {
if (watch) {
log(
chalk.magenta(
`Start watching ${slash(srcPath).replace(
`${cwd}/`,
""
)} directory...`
)
);
const watcher = chokidar.watch(patterns, {
ignoreInitial: true,
});
const files = [];
function compileFiles() {
while (files.length) {
createStream(files.pop());
}
}
const debouncedCompileFiles = lodash.debounce(compileFiles, 1000);
watcher.on("all", (event, fullPath) => {
const relPath = fullPath.replace(srcPath, "");
log(
`[${event}] ${slash(join(srcPath, relPath)).replace(`${cwd}/`, "")}`
);
if (!existsSync(fullPath)) return;
if (statSync(fullPath).isFile()) {
if (!files.includes(fullPath)) files.push(fullPath);
debouncedCompileFiles();
}
});
process.once("SIGINT", () => {
watcher.close();
});
dispose?.push(() => watcher.close());
}
resolve();
});
});
}