@modern-js/babel-compiler 2.69.4 → 3.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/cjs/build.js +68 -73
  2. package/dist/cjs/buildWatch.js +111 -116
  3. package/dist/cjs/compiler.js +103 -116
  4. package/dist/cjs/compilerErrorResult.js +61 -56
  5. package/dist/cjs/constants.js +36 -28
  6. package/dist/cjs/defaults.js +46 -38
  7. package/dist/cjs/getFinalOption.js +82 -83
  8. package/dist/cjs/index.js +92 -44
  9. package/dist/cjs/type.js +17 -15
  10. package/dist/cjs/utils.js +34 -37
  11. package/dist/cjs/validate.js +70 -64
  12. package/dist/esm/build.mjs +42 -0
  13. package/dist/esm/buildWatch.mjs +78 -0
  14. package/dist/esm/compiler.mjs +76 -0
  15. package/dist/esm/compilerErrorResult.mjs +34 -0
  16. package/dist/esm/constants.mjs +7 -0
  17. package/dist/esm/defaults.mjs +17 -0
  18. package/dist/esm/getFinalOption.mjs +50 -0
  19. package/dist/{esm-node/index.js → esm/index.mjs} +7 -14
  20. package/dist/esm/utils.mjs +5 -0
  21. package/dist/esm/validate.mjs +32 -0
  22. package/dist/esm-node/build.mjs +42 -0
  23. package/dist/esm-node/buildWatch.mjs +78 -0
  24. package/dist/esm-node/compiler.mjs +76 -0
  25. package/dist/esm-node/compilerErrorResult.mjs +34 -0
  26. package/dist/esm-node/constants.mjs +7 -0
  27. package/dist/esm-node/defaults.mjs +17 -0
  28. package/dist/esm-node/getFinalOption.mjs +50 -0
  29. package/dist/esm-node/index.mjs +14 -0
  30. package/dist/esm-node/utils.mjs +5 -0
  31. package/dist/esm-node/validate.mjs +32 -0
  32. package/package.json +24 -17
  33. package/rslib.config.mts +4 -0
  34. package/rstest.config.ts +7 -0
  35. package/dist/esm/build.js +0 -105
  36. package/dist/esm/buildWatch.js +0 -157
  37. package/dist/esm/compiler.js +0 -95
  38. package/dist/esm/compilerErrorResult.js +0 -71
  39. package/dist/esm/constants.js +0 -9
  40. package/dist/esm/defaults.js +0 -19
  41. package/dist/esm/getFinalOption.js +0 -68
  42. package/dist/esm/index.js +0 -46
  43. package/dist/esm/utils.js +0 -7
  44. package/dist/esm/validate.js +0 -44
  45. package/dist/esm-node/build.js +0 -57
  46. package/dist/esm-node/buildWatch.js +0 -89
  47. package/dist/esm-node/compiler.js +0 -95
  48. package/dist/esm-node/compilerErrorResult.js +0 -39
  49. package/dist/esm-node/constants.js +0 -9
  50. package/dist/esm-node/defaults.js +0 -19
  51. package/dist/esm-node/getFinalOption.js +0 -67
  52. package/dist/esm-node/utils.js +0 -8
  53. package/dist/esm-node/validate.js +0 -44
  54. /package/dist/esm/{type.js → type.mjs} +0 -0
  55. /package/dist/esm-node/{type.js → type.mjs} +0 -0
package/dist/cjs/utils.js CHANGED
@@ -1,42 +1,39 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var utils_exports = {};
30
- __export(utils_exports, {
31
- addSourceMappingUrl: () => addSourceMappingUrl
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ addSourceMappingUrl: ()=>addSourceMappingUrl
32
28
  });
33
- module.exports = __toCommonJS(utils_exports);
34
- var path = __toESM(require("path"));
29
+ const external_path_namespaceObject = require("path");
35
30
  function addSourceMappingUrl(code, loc) {
36
- return `${code}
37
- //# sourceMappingURL=${path.normalize(path.basename(loc))}`;
31
+ return `${code}\n//# sourceMappingURL=${external_path_namespaceObject.normalize(external_path_namespaceObject.basename(loc))}`;
38
32
  }
39
- // Annotate the CommonJS export names for ESM import in node:
40
- 0 && (module.exports = {
41
- addSourceMappingUrl
33
+ exports.addSourceMappingUrl = __webpack_exports__.addSourceMappingUrl;
34
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
35
+ "addSourceMappingUrl"
36
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
37
+ Object.defineProperty(exports, '__esModule', {
38
+ value: true
42
39
  });
@@ -1,72 +1,78 @@
1
1
  "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var validate_exports = {};
20
- __export(validate_exports, {
21
- sourceDirAndFileNamesValidMessage: () => sourceDirAndFileNamesValidMessage,
22
- validate: () => validate,
23
- validateSourceDirAndFileNames: () => validateSourceDirAndFileNames,
24
- validateWatchDir: () => validateWatchDir,
25
- watchDirValidMessage: () => watchDirValidMessage
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ sourceDirAndFileNamesValidMessage: ()=>sourceDirAndFileNamesValidMessage,
28
+ validateSourceDirAndFileNames: ()=>validateSourceDirAndFileNames,
29
+ validateWatchDir: ()=>validateWatchDir,
30
+ watchDirValidMessage: ()=>watchDirValidMessage,
31
+ validate: ()=>validate
26
32
  });
27
- module.exports = __toCommonJS(validate_exports);
28
- var import_utils = require("@modern-js/utils");
29
- const sourceDirAndFileNamesValidMessage = "At least one of the sourceDir and filenames configurations must be configured";
30
- const watchDirValidMessage = "should set watchDir when enableWatch is true";
31
- const validateSourceDirAndFileNames = (compilerOptions) => {
32
- const { sourceDir, filenames, quiet } = compilerOptions;
33
- if (!sourceDir && !filenames) {
34
- if (!quiet) {
35
- import_utils.logger.error(sourceDirAndFileNamesValidMessage);
33
+ const utils_namespaceObject = require("@modern-js/utils");
34
+ const sourceDirAndFileNamesValidMessage = 'At least one of the sourceDir and filenames configurations must be configured';
35
+ const watchDirValidMessage = 'should set watchDir when enableWatch is true';
36
+ const validateSourceDirAndFileNames = (compilerOptions)=>{
37
+ const { sourceDir, filenames, quiet } = compilerOptions;
38
+ if (!sourceDir && !filenames) {
39
+ if (!quiet) utils_namespaceObject.logger.error(sourceDirAndFileNamesValidMessage);
40
+ return {
41
+ code: 1,
42
+ message: sourceDirAndFileNamesValidMessage,
43
+ virtualDists: []
44
+ };
36
45
  }
37
- return {
38
- code: 1,
39
- message: sourceDirAndFileNamesValidMessage,
40
- virtualDists: []
41
- };
42
- }
43
- return null;
46
+ return null;
44
47
  };
45
- const validateWatchDir = (compilerOptions) => {
46
- const { watchDir, enableWatch, quiet } = compilerOptions;
47
- if (enableWatch && !watchDir) {
48
- if (!quiet) {
49
- import_utils.logger.error(watchDirValidMessage);
48
+ const validateWatchDir = (compilerOptions)=>{
49
+ const { watchDir, enableWatch, quiet } = compilerOptions;
50
+ if (enableWatch && !watchDir) {
51
+ if (!quiet) utils_namespaceObject.logger.error(watchDirValidMessage);
52
+ return {
53
+ code: 1,
54
+ message: watchDirValidMessage,
55
+ virtualDists: []
56
+ };
50
57
  }
51
- return {
52
- code: 1,
53
- message: watchDirValidMessage,
54
- virtualDists: []
55
- };
56
- }
57
- return null;
58
+ return null;
58
59
  };
59
- const validate = (compilerOptions) => {
60
- if (compilerOptions.enableWatch) {
61
- return validateWatchDir(compilerOptions);
62
- }
63
- return validateSourceDirAndFileNames(compilerOptions);
60
+ const validate = (compilerOptions)=>{
61
+ if (compilerOptions.enableWatch) return validateWatchDir(compilerOptions);
62
+ return validateSourceDirAndFileNames(compilerOptions);
64
63
  };
65
- // Annotate the CommonJS export names for ESM import in node:
66
- 0 && (module.exports = {
67
- sourceDirAndFileNamesValidMessage,
68
- validate,
69
- validateSourceDirAndFileNames,
70
- validateWatchDir,
71
- watchDirValidMessage
64
+ exports.sourceDirAndFileNamesValidMessage = __webpack_exports__.sourceDirAndFileNamesValidMessage;
65
+ exports.validate = __webpack_exports__.validate;
66
+ exports.validateSourceDirAndFileNames = __webpack_exports__.validateSourceDirAndFileNames;
67
+ exports.validateWatchDir = __webpack_exports__.validateWatchDir;
68
+ exports.watchDirValidMessage = __webpack_exports__.watchDirValidMessage;
69
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
70
+ "sourceDirAndFileNamesValidMessage",
71
+ "validate",
72
+ "validateSourceDirAndFileNames",
73
+ "validateWatchDir",
74
+ "watchDirValidMessage"
75
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
76
+ Object.defineProperty(exports, '__esModule', {
77
+ value: true
72
78
  });
@@ -0,0 +1,42 @@
1
+ import { fs, logger } from "@modern-js/utils";
2
+ import { compiler } from "./compiler";
3
+ import { defaultDistFileExtMap } from "./constants";
4
+ const build = async (option, babelConfig = {})=>{
5
+ const { rootDir, enableVirtualDist, filenames, clean, distDir, distFileExtMap = defaultDistFileExtMap, verbose = false, quiet = false } = option;
6
+ const virtualDists = [];
7
+ if (clean) await fs.remove(distDir);
8
+ fs.ensureDir(distDir);
9
+ const messageDetails = [];
10
+ for (const filename of filenames)try {
11
+ const dist = compiler({
12
+ rootDir,
13
+ enableVirtualDist,
14
+ filepath: filename,
15
+ distDir,
16
+ verbose,
17
+ quiet,
18
+ babelConfig,
19
+ distFileExtMap
20
+ });
21
+ if (enableVirtualDist && dist) virtualDists.push(dist);
22
+ } catch (e) {
23
+ messageDetails.push({
24
+ filename,
25
+ content: e.toString()
26
+ });
27
+ }
28
+ const happenError = messageDetails.length > 0;
29
+ if (!quiet) if (happenError) logger.error(`Compilation failure ${messageDetails.length} ${1 !== messageDetails.length ? 'files' : 'file'} with Babel.`);
30
+ else logger.info(`Successfully compiled ${filenames.length} ${1 !== filenames.length ? 'files' : 'file'} with Babel.`);
31
+ if (happenError) return {
32
+ code: 1,
33
+ message: `Compilation failure ${messageDetails.length} ${1 !== messageDetails.length ? 'files' : 'file'} with Babel.`,
34
+ messageDetails
35
+ };
36
+ return {
37
+ code: 0,
38
+ message: `Successfully compiled ${filenames.length} ${1 !== filenames.length ? 'files' : 'file'} with Babel.`,
39
+ virtualDists
40
+ };
41
+ };
42
+ export { build };
@@ -0,0 +1,78 @@
1
+ import { EventEmitter } from "events";
2
+ import { normalize, relative } from "path";
3
+ import { WatchChangeType, logger, watch } from "@modern-js/utils";
4
+ import { build } from "./build";
5
+ import { CompilerErrorResult } from "./compilerErrorResult";
6
+ const BuildWatchEvent = {
7
+ firstCompiler: 'first-compiler',
8
+ compiling: 'compiling',
9
+ watchingCompiler: 'watching-compiler'
10
+ };
11
+ class BuildWatchEmitter extends EventEmitter {
12
+ setInitFn(fn) {
13
+ this._initFn = fn;
14
+ }
15
+ async watch() {
16
+ if ('function' == typeof this._initFn) return this._initFn(this);
17
+ return null;
18
+ }
19
+ }
20
+ const runBuildWatch = async (option, babelConfig = {}, emitter)=>{
21
+ emitter.emit(BuildWatchEvent.compiling);
22
+ const errorResult = new CompilerErrorResult();
23
+ const watchDir = option.watchDir;
24
+ const { distDir, quiet } = option;
25
+ const firstBuildResult = await build(option, babelConfig);
26
+ const { code } = firstBuildResult;
27
+ if (1 === code) {
28
+ errorResult.init(firstBuildResult);
29
+ emitter.emit(BuildWatchEvent.firstCompiler, errorResult.value);
30
+ } else emitter.emit(BuildWatchEvent.firstCompiler, firstBuildResult);
31
+ return watch(`${watchDir}/**/*.{js,jsx,ts,tsx}`, async ({ changeType, changedFilePath })=>{
32
+ emitter.emit(BuildWatchEvent.compiling);
33
+ if (changeType === WatchChangeType.UNLINK) {
34
+ const removeFiles = [
35
+ normalize(`./${distDir}/${relative(watchDir, changedFilePath)}`)
36
+ ];
37
+ if (!quiet) logger.info(`remove file: ${removeFiles.join(',')}`);
38
+ const result = {
39
+ code: 0,
40
+ message: `remove file: ${removeFiles.join(',')}`,
41
+ removeFiles
42
+ };
43
+ emitter.emit(BuildWatchEvent.watchingCompiler, result);
44
+ return;
45
+ }
46
+ const result = await build({
47
+ ...option,
48
+ filenames: [
49
+ changedFilePath
50
+ ]
51
+ }, babelConfig);
52
+ if (1 === result.code) {
53
+ errorResult.update(result.messageDetails || []);
54
+ emitter.emit(BuildWatchEvent.watchingCompiler, errorResult.value);
55
+ quiet || logger.info(errorResult.value.message);
56
+ } else {
57
+ errorResult.removeByFileName(changedFilePath);
58
+ if (errorResult.checkExistError()) {
59
+ emitter.emit(BuildWatchEvent.watchingCompiler, {
60
+ ...errorResult.value,
61
+ virtualDists: result.virtualDists
62
+ });
63
+ quiet || logger.info(errorResult.value.message);
64
+ } else {
65
+ emitter.emit(BuildWatchEvent.watchingCompiler, result);
66
+ quiet || logger.info(result.message);
67
+ }
68
+ }
69
+ }, [
70
+ `${watchDir}/**/*.d.ts`
71
+ ]);
72
+ };
73
+ const buildWatch = (option, babelConfig = {})=>{
74
+ const buildWatchEmitter = new BuildWatchEmitter();
75
+ buildWatchEmitter.setInitFn(runBuildWatch.bind(null, option, babelConfig));
76
+ return buildWatchEmitter;
77
+ };
78
+ export { BuildWatchEmitter, BuildWatchEvent, buildWatch, runBuildWatch };
@@ -0,0 +1,76 @@
1
+ import { basename, dirname, extname, join, relative } from "path";
2
+ import { transformFileSync } from "@babel/core";
3
+ import { fs, logger } from "@modern-js/utils";
4
+ import { defaultDistFileExtMap } from "./constants";
5
+ import { addSourceMappingUrl } from "./utils";
6
+ const defaultDistDir = 'dist';
7
+ const isRes = (r)=>Boolean(r);
8
+ const getDistFilePath = (option)=>{
9
+ const { filepath, rootDir, distDir, extMap } = option;
10
+ const ext = extname(filepath);
11
+ return join(distDir, relative(rootDir, filepath).replace(ext, extMap[ext]));
12
+ };
13
+ const resolveSourceMap = (option)=>{
14
+ const { babelRes, sourceFilePath, distFilePath, enableVirtualDist = false } = option;
15
+ const mapLoc = `${distFilePath}.map`;
16
+ babelRes.code = addSourceMappingUrl(babelRes.code, mapLoc);
17
+ if (babelRes.map) {
18
+ babelRes.map.file = basename(distFilePath);
19
+ babelRes.map.sources = [
20
+ relative(dirname(distFilePath), sourceFilePath)
21
+ ];
22
+ }
23
+ const sourceMapVirtualDist = {
24
+ sourcemap: JSON.stringify(babelRes.map),
25
+ sourceMapPath: mapLoc
26
+ };
27
+ if (enableVirtualDist) return sourceMapVirtualDist;
28
+ fs.ensureDirSync(dirname(mapLoc));
29
+ fs.writeFileSync(mapLoc, JSON.stringify(babelRes.map));
30
+ return sourceMapVirtualDist;
31
+ };
32
+ const compiler = (option)=>{
33
+ const { filepath, rootDir, enableVirtualDist = false, distDir = join(dirname(rootDir), defaultDistDir), verbose = false, babelConfig = {}, distFileExtMap = defaultDistFileExtMap, quiet = false } = option;
34
+ const babelRes = transformFileSync(filepath, babelConfig);
35
+ let virtualDist = null;
36
+ if (!isRes(babelRes)) throw new Error(`${filepath} happen error`);
37
+ const distFilePath = getDistFilePath({
38
+ filepath,
39
+ rootDir,
40
+ distDir,
41
+ extMap: distFileExtMap
42
+ });
43
+ if (enableVirtualDist) virtualDist = {
44
+ distPath: distFilePath,
45
+ sourceMapPath: '',
46
+ code: '',
47
+ sourcemap: ''
48
+ };
49
+ if (babelRes?.map && babelConfig.sourceMaps && 'inline' !== babelConfig.sourceMaps) if (virtualDist) virtualDist = {
50
+ ...virtualDist,
51
+ ...resolveSourceMap({
52
+ babelRes,
53
+ sourceFilePath: filepath,
54
+ distFilePath,
55
+ enableVirtualDist
56
+ })
57
+ };
58
+ else resolveSourceMap({
59
+ babelRes,
60
+ sourceFilePath: filepath,
61
+ distFilePath,
62
+ enableVirtualDist
63
+ });
64
+ if (virtualDist) virtualDist = {
65
+ ...virtualDist,
66
+ distPath: distFilePath,
67
+ code: babelRes.code
68
+ };
69
+ else {
70
+ fs.ensureDirSync(dirname(distFilePath));
71
+ fs.writeFileSync(distFilePath, babelRes.code);
72
+ }
73
+ if (verbose && !quiet) logger.info(`${filepath} => ${distFilePath}`);
74
+ return virtualDist;
75
+ };
76
+ export { compiler, getDistFilePath, isRes, resolveSourceMap };
@@ -0,0 +1,34 @@
1
+ class CompilerErrorResult {
2
+ init(initErrorResult) {
3
+ this._messageDetails = initErrorResult?.messageDetails || [];
4
+ }
5
+ update(messageDetails) {
6
+ for (const messageDetail of messageDetails){
7
+ const addError = !this._messageDetails.some((detail)=>{
8
+ if (detail.filename === messageDetail.filename) {
9
+ detail.content = messageDetail.content;
10
+ return true;
11
+ }
12
+ return false;
13
+ });
14
+ if (addError) this._messageDetails.push(messageDetail);
15
+ }
16
+ }
17
+ removeByFileName(filename) {
18
+ this._messageDetails = this._messageDetails.filter((detail)=>detail.filename !== filename);
19
+ }
20
+ get value() {
21
+ return {
22
+ code: 1,
23
+ message: `Compilation failure ${this._messageDetails?.length} files with Babel.`,
24
+ messageDetails: this._messageDetails
25
+ };
26
+ }
27
+ checkExistError() {
28
+ return this._messageDetails.length > 0;
29
+ }
30
+ constructor(initErrorResult){
31
+ this.init(initErrorResult);
32
+ }
33
+ }
34
+ export { CompilerErrorResult };
@@ -0,0 +1,7 @@
1
+ const defaultDistFileExtMap = {
2
+ '.js': '.js',
3
+ '.jsx': '.js',
4
+ '.ts': '.js',
5
+ '.tsx': '.js'
6
+ };
7
+ export { defaultDistFileExtMap };
@@ -0,0 +1,17 @@
1
+ import { defaultDistFileExtMap } from "./constants";
2
+ const defaultOptions = {
3
+ enableWatch: false,
4
+ enableVirtualDist: false,
5
+ extensions: [],
6
+ filenames: [],
7
+ distFileExtMap: defaultDistFileExtMap,
8
+ ignore: [],
9
+ quiet: false,
10
+ verbose: false,
11
+ clean: false
12
+ };
13
+ const mergeDefaultOption = (compilerOptions)=>({
14
+ ...defaultOptions,
15
+ ...compilerOptions
16
+ });
17
+ export { mergeDefaultOption };
@@ -0,0 +1,50 @@
1
+ import { DEFAULT_EXTENSIONS } from "@babel/core";
2
+ import { glob } from "@modern-js/utils";
3
+ import { mergeDefaultOption } from "./defaults";
4
+ const getGlobPattern = (dir, extensions)=>{
5
+ if (extensions.length > 1) return `${dir}/**/*{${extensions.join(',')}}`;
6
+ if (1 === extensions.length) return `${dir}/**/*${extensions[0]}`;
7
+ return `${dir}/**/*`;
8
+ };
9
+ const getFinalExtensions = (extensions)=>{
10
+ const isExtensions = (ext)=>Array.isArray(ext);
11
+ const isExtensionsFunc = (ext)=>'function' == typeof ext;
12
+ if (isExtensions(extensions)) return [
13
+ ...extensions,
14
+ ...DEFAULT_EXTENSIONS
15
+ ];
16
+ if (isExtensionsFunc(extensions)) return extensions(DEFAULT_EXTENSIONS);
17
+ return DEFAULT_EXTENSIONS;
18
+ };
19
+ const getFilesFromDir = ({ dir, finalExt = [], ignore = [] })=>{
20
+ let globFindFilenames = [];
21
+ const globPattern = getGlobPattern(dir, finalExt);
22
+ globFindFilenames = glob.sync(globPattern, {
23
+ ignore
24
+ });
25
+ return globFindFilenames;
26
+ };
27
+ const getFinalCompilerOption = (option)=>{
28
+ const optionWithDefault = mergeDefaultOption(option);
29
+ const { sourceDir, ignore, enableWatch = false, watchDir, extensions = DEFAULT_EXTENSIONS } = option;
30
+ let globFindFilenames = [];
31
+ const finalExt = getFinalExtensions(extensions);
32
+ if (sourceDir) globFindFilenames = getFilesFromDir({
33
+ dir: sourceDir,
34
+ ignore,
35
+ finalExt
36
+ });
37
+ if (enableWatch) globFindFilenames = getFilesFromDir({
38
+ dir: watchDir,
39
+ ignore,
40
+ finalExt
41
+ });
42
+ return {
43
+ ...optionWithDefault,
44
+ filenames: [
45
+ ...optionWithDefault.filenames,
46
+ ...globFindFilenames
47
+ ]
48
+ };
49
+ };
50
+ export { getFilesFromDir, getFinalCompilerOption, getFinalExtensions, getGlobPattern };
@@ -2,20 +2,13 @@ import { build } from "./build";
2
2
  import { buildWatch } from "./buildWatch";
3
3
  import { getFinalCompilerOption } from "./getFinalOption";
4
4
  import { validate } from "./validate";
5
+ export * from "./buildWatch";
6
+ export * from "./type";
5
7
  async function compiler(compilerOptions, babelOptions = {}) {
6
- const validRet = validate(compilerOptions);
7
- if (validRet) {
8
- return validRet;
9
- }
10
- const finalCompilerOption = getFinalCompilerOption(compilerOptions);
11
- if (compilerOptions.enableWatch) {
12
- return buildWatch(finalCompilerOption, babelOptions);
13
- } else {
8
+ const validRet = validate(compilerOptions);
9
+ if (validRet) return validRet;
10
+ const finalCompilerOption = getFinalCompilerOption(compilerOptions);
11
+ if (compilerOptions.enableWatch) return buildWatch(finalCompilerOption, babelOptions);
14
12
  return build(finalCompilerOption, babelOptions);
15
- }
16
13
  }
17
- export * from "./buildWatch";
18
- export * from "./type";
19
- export {
20
- compiler
21
- };
14
+ export { compiler };
@@ -0,0 +1,5 @@
1
+ import { basename, normalize } from "path";
2
+ function addSourceMappingUrl(code, loc) {
3
+ return `${code}\n//# sourceMappingURL=${normalize(basename(loc))}`;
4
+ }
5
+ export { addSourceMappingUrl };
@@ -0,0 +1,32 @@
1
+ import { logger } from "@modern-js/utils";
2
+ const sourceDirAndFileNamesValidMessage = 'At least one of the sourceDir and filenames configurations must be configured';
3
+ const watchDirValidMessage = 'should set watchDir when enableWatch is true';
4
+ const validateSourceDirAndFileNames = (compilerOptions)=>{
5
+ const { sourceDir, filenames, quiet } = compilerOptions;
6
+ if (!sourceDir && !filenames) {
7
+ if (!quiet) logger.error(sourceDirAndFileNamesValidMessage);
8
+ return {
9
+ code: 1,
10
+ message: sourceDirAndFileNamesValidMessage,
11
+ virtualDists: []
12
+ };
13
+ }
14
+ return null;
15
+ };
16
+ const validateWatchDir = (compilerOptions)=>{
17
+ const { watchDir, enableWatch, quiet } = compilerOptions;
18
+ if (enableWatch && !watchDir) {
19
+ if (!quiet) logger.error(watchDirValidMessage);
20
+ return {
21
+ code: 1,
22
+ message: watchDirValidMessage,
23
+ virtualDists: []
24
+ };
25
+ }
26
+ return null;
27
+ };
28
+ const validate = (compilerOptions)=>{
29
+ if (compilerOptions.enableWatch) return validateWatchDir(compilerOptions);
30
+ return validateSourceDirAndFileNames(compilerOptions);
31
+ };
32
+ export { sourceDirAndFileNamesValidMessage, validate, validateSourceDirAndFileNames, validateWatchDir, watchDirValidMessage };
@@ -0,0 +1,42 @@
1
+ import { fs, logger } from "@modern-js/utils";
2
+ import { compiler } from "./compiler.mjs";
3
+ import { defaultDistFileExtMap } from "./constants.mjs";
4
+ const build = async (option, babelConfig = {})=>{
5
+ const { rootDir, enableVirtualDist, filenames, clean, distDir, distFileExtMap = defaultDistFileExtMap, verbose = false, quiet = false } = option;
6
+ const virtualDists = [];
7
+ if (clean) await fs.remove(distDir);
8
+ fs.ensureDir(distDir);
9
+ const messageDetails = [];
10
+ for (const filename of filenames)try {
11
+ const dist = compiler({
12
+ rootDir,
13
+ enableVirtualDist,
14
+ filepath: filename,
15
+ distDir,
16
+ verbose,
17
+ quiet,
18
+ babelConfig,
19
+ distFileExtMap
20
+ });
21
+ if (enableVirtualDist && dist) virtualDists.push(dist);
22
+ } catch (e) {
23
+ messageDetails.push({
24
+ filename,
25
+ content: e.toString()
26
+ });
27
+ }
28
+ const happenError = messageDetails.length > 0;
29
+ if (!quiet) if (happenError) logger.error(`Compilation failure ${messageDetails.length} ${1 !== messageDetails.length ? 'files' : 'file'} with Babel.`);
30
+ else logger.info(`Successfully compiled ${filenames.length} ${1 !== filenames.length ? 'files' : 'file'} with Babel.`);
31
+ if (happenError) return {
32
+ code: 1,
33
+ message: `Compilation failure ${messageDetails.length} ${1 !== messageDetails.length ? 'files' : 'file'} with Babel.`,
34
+ messageDetails
35
+ };
36
+ return {
37
+ code: 0,
38
+ message: `Successfully compiled ${filenames.length} ${1 !== filenames.length ? 'files' : 'file'} with Babel.`,
39
+ virtualDists
40
+ };
41
+ };
42
+ export { build };