@modern-js/babel-compiler 1.1.4 → 1.2.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # @modern-js/babel-compiler
2
2
 
3
+ ## 1.2.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 55e18278: chore: remove unused dependencies and devDependencies
8
+ - Updated dependencies [4c792f68]
9
+ - Updated dependencies [a7f42f48]
10
+ - @modern-js/utils@1.3.3
11
+
12
+ ## 1.2.1
13
+
14
+ ### Patch Changes
15
+
16
+ - 83166714: change .npmignore
17
+ - Updated dependencies [83166714]
18
+ - @modern-js/utils@1.2.2
19
+
20
+ ## 1.2.0
21
+
22
+ ### Minor Changes
23
+
24
+ - cfe11628: Make Modern.js self bootstraping
25
+
26
+ ### Patch Changes
27
+
28
+ - 146dcd85: fix test case in babel compiler
29
+ - 1ebc7ee2: fix: @babel/core version
30
+ - Updated dependencies [2da09c69]
31
+ - Updated dependencies [c3d46ee4]
32
+ - Updated dependencies [cfe11628]
33
+ - @modern-js/utils@1.2.0
34
+
3
35
  ## 1.1.4
4
36
 
5
37
  ### Patch Changes
@@ -1,7 +1,7 @@
1
1
  import type { IOptions } from 'glob';
2
2
  import { Extensions, ExtensionsFunc, ICompilerOptions, IFinaleCompilerOptions } from './type';
3
3
  export declare const getGlobPattern: (dir: string, extensions: Extensions) => string;
4
- export declare const getFinalExtensions: (extensions: Extensions | ExtensionsFunc | undefined) => Extensions;
4
+ export declare const getFinalExtensions: (extensions: Extensions | ExtensionsFunc | undefined) => string[];
5
5
  export declare const getFilesFromDir: ({
6
6
  dir,
7
7
  finalExt,
package/jest.config.js ADDED
@@ -0,0 +1,8 @@
1
+ const sharedConfig = require('@scripts/jest-config');
2
+
3
+ /** @type {import('@jest/types').Config.InitialOptions} */
4
+ module.exports = {
5
+ // eslint-disable-next-line node/no-unsupported-features/es-syntax
6
+ ...sharedConfig,
7
+ rootDir: __dirname,
8
+ };
package/modern.config.js CHANGED
@@ -1,19 +1,6 @@
1
1
  /** @type {import('@modern-js/module-tools').UserConfig} */
2
2
  module.exports = {
3
3
  output: {
4
- // enableTsChecker: true,
5
4
  disableSourceMap: true,
6
5
  },
7
- testing: {
8
- jest: {
9
- // Reasons for setting up testRunner:
10
- // https://github.com/facebook/jest/issues/10529
11
- // https://jestjs.io/blog/2020/05/05/jest-26
12
- testRunner: 'jest-jasmine2',
13
- testEnvironment: 'node',
14
- collectCoverage: true,
15
- collectCoverageFrom: ['./src/**/*.ts'],
16
- coveragePathIgnorePatterns: ['/node_modules/', '/tests'],
17
- },
18
- },
19
6
  };
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.1.4",
14
+ "version": "1.2.2",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
@@ -20,6 +20,7 @@
20
20
  "exports": {
21
21
  ".": {
22
22
  "node": {
23
+ "jsnext:source": "./src/index.ts",
23
24
  "import": "./dist/js/modern/index.js",
24
25
  "require": "./dist/js/node/index.js"
25
26
  },
@@ -27,9 +28,9 @@
27
28
  }
28
29
  },
29
30
  "dependencies": {
30
- "@babel/core": "^7.15.0",
31
+ "@babel/core": "7.16.7",
31
32
  "@babel/runtime": "^7",
32
- "@modern-js/utils": "^1.1.6",
33
+ "@modern-js/utils": "^1.3.3",
33
34
  "chokidar": "^3.5.2",
34
35
  "glob": "^7.1.6"
35
36
  },
@@ -40,10 +41,10 @@
40
41
  "@types/glob": "^7.1.4",
41
42
  "@types/jest": "^26",
42
43
  "@types/node": "^14",
43
- "jest-jasmine2": "^27.2.2",
44
44
  "typescript": "^4",
45
- "@modern-js/plugin-testing": "^1.2.2",
46
- "@modern-js/module-tools": "^1.1.4"
45
+ "@scripts/build": "0.0.0",
46
+ "jest": "^27",
47
+ "@scripts/jest-config": "0.0.0"
47
48
  },
48
49
  "sideEffects": false,
49
50
  "modernConfig": {
@@ -58,7 +59,7 @@
58
59
  "scripts": {
59
60
  "new": "modern new",
60
61
  "build": "modern build",
61
- "test": "modern test --passWithNoTests"
62
+ "test": "jest --passWithNoTests"
62
63
  },
63
64
  "readme": "\n<p align=\"center\">\n <a href=\"https://modernjs.dev\" target=\"blank\"><img src=\"https://lf3-static.bytednsdoc.com/obj/eden-cn/ylaelkeh7nuhfnuhf/modernjs-cover.png\" width=\"300\" alt=\"Modern.js Logo\" /></a>\n</p>\n<p align=\"center\">\n现代 Web 工程体系\n <br/>\n <a href=\"https://modernjs.dev\" target=\"blank\">\n modernjs.dev\n </a>\n</p>\n<p align=\"center\">\n The meta-framework suite designed from scratch for frontend-focused modern web development\n</p>\n\n# Introduction\n\n> The doc site ([modernjs.dev](https://modernjs.dev)) and articles are only available in Chinese for now, we are planning to add English versions soon.\n\n- [Modern.js: Hello, World!](https://zhuanlan.zhihu.com/p/426707646)\n\n## Getting Started\n\n- [Quick Start](https://modernjs.dev/docs/start)\n- [Guides](https://modernjs.dev/docs/guides)\n- [API References](https://modernjs.dev/docs/apis)\n\n## Contributing\n\n- [Contributing Guide](https://github.com/modern-js-dev/modern.js/blob/main/CONTRIBUTING.md)\n"
64
65
  }
@@ -24,7 +24,6 @@ describe('test build', () => {
24
24
  await build({ rootDir: srcDir, filenames, distDir });
25
25
  const globFindFiles = glob.sync(`${distDir}/**/*.js`);
26
26
  expect(globFindFiles.length).toBe(1);
27
- fs.removeSync(distDir);
28
27
  });
29
28
 
30
29
  it('build with enableVirtualDist and success', async () => {
@@ -80,7 +79,6 @@ describe('test build', () => {
80
79
  });
81
80
  const globFindFiles = glob.sync(`${distDir}/**/*.js`);
82
81
  expect(globFindFiles.length).toBe(1);
83
- fs.removeSync(distDir);
84
82
  });
85
83
 
86
84
  it('build multiple files and success', async () => {
@@ -39,7 +39,9 @@ describe('test build watch', () => {
39
39
  expect(ret).toBe(null);
40
40
  });
41
41
 
42
- it('runBuildWatch and success', async done => {
42
+ it('runBuildWatch and success', async () => {
43
+ let done: any;
44
+ const promise = new Promise(resolve => (done = resolve));
43
45
  let compiling = false;
44
46
  const emitter = new BuildWatchEmitter();
45
47
  emitter.on(BuildWatchEvent.firstCompiler, (result: ICompilerResult) => {
@@ -65,9 +67,12 @@ describe('test build watch', () => {
65
67
  fs.ensureFileSync(path.join(srcDir, 'far.js'));
66
68
  compiling = true;
67
69
  });
70
+ return promise;
68
71
  });
69
72
 
70
- it('runBuildWatch and fail', async done => {
73
+ it('runBuildWatch and fail', async () => {
74
+ let done: any;
75
+ const promise = new Promise(resolve => (done = resolve));
71
76
  const emitter = new BuildWatchEmitter();
72
77
  emitter.on(BuildWatchEvent.firstCompiler, (result: ICompilerResult) => {
73
78
  expect(result.code).toBe(1);
@@ -89,9 +94,12 @@ describe('test build watch', () => {
89
94
  fs.ensureFileSync(path.join(srcDir, 'error1.js'));
90
95
  fs.writeFileSync(path.join(srcDir, 'error1.js'), 'conta a = 1');
91
96
  });
97
+ return promise;
92
98
  });
93
99
 
94
- it('buildWatch and success', async done => {
100
+ it('buildWatch and success', async () => {
101
+ let done: any;
102
+ const promise = new Promise(resolve => (done = resolve));
95
103
  const emitter = buildWatch({
96
104
  rootDir: srcDir,
97
105
  watchDir: srcDir,
@@ -125,9 +133,12 @@ describe('test build watch', () => {
125
133
  compiling = true;
126
134
  });
127
135
  }
136
+ return promise;
128
137
  });
129
138
 
130
- it('buildWatch and fail', async done => {
139
+ it('buildWatch and fail', async () => {
140
+ let done: any;
141
+ const promise = new Promise(resolve => (done = resolve));
131
142
  const emitter = buildWatch({
132
143
  rootDir: srcDir,
133
144
  watchDir: srcDir,
@@ -161,9 +172,12 @@ describe('test build watch', () => {
161
172
  compiling = true;
162
173
  });
163
174
  }
175
+ return promise;
164
176
  });
165
177
 
166
- it('buildWatch and remove file', async done => {
178
+ it('buildWatch and remove file', async () => {
179
+ let done: any;
180
+ const promise = new Promise(resolve => (done = resolve));
167
181
  const emitter = buildWatch({
168
182
  rootDir: srcDir,
169
183
  watchDir: srcDir,
@@ -190,9 +204,12 @@ describe('test build watch', () => {
190
204
  fs.removeSync(path.join(srcDir, 'far.js'));
191
205
  });
192
206
  }
207
+ return promise;
193
208
  });
194
209
 
195
- it('buildWatch and reRight file', async done => {
210
+ it('buildWatch and reRight file', async () => {
211
+ let done: any;
212
+ const promise = new Promise(resolve => (done = resolve));
196
213
  fs.ensureFileSync(path.join(srcDir, 'error1.js'));
197
214
  fs.writeFileSync(path.join(srcDir, 'error1.js'), 'cast a = 1;');
198
215
  const emitter = buildWatch({
@@ -221,6 +238,7 @@ describe('test build watch', () => {
221
238
  fs.writeFileSync(path.join(srcDir, 'error1.js'), 'const a = 1;');
222
239
  });
223
240
  }
241
+ return promise;
224
242
  });
225
243
 
226
244
  afterEach(() => {
@@ -7,9 +7,7 @@
7
7
  "outDir": "./out",
8
8
  "emitDeclarationOnly": true,
9
9
  "isolatedModules": true,
10
- "paths": {
11
- "@/*": ["../src/*"]
12
- },
10
+ "paths": {},
13
11
  "types": ["node", "jest"]
14
12
  }
15
13
  }
package/tsconfig.json CHANGED
@@ -7,9 +7,7 @@
7
7
  "outDir": "./out",
8
8
  "emitDeclarationOnly": true,
9
9
  "isolatedModules": true,
10
- "paths": {
11
- "@/*": ["./src/*"]
12
- },
10
+ "paths": {},
13
11
  "types": ["node", "jest"]
14
12
  },
15
13
  "include": ["src"]
package/src/build.ts DELETED
@@ -1,95 +0,0 @@
1
- import { fs, logger } from '@modern-js/utils';
2
- import { defaultDistFileExtMap } from './constants';
3
- import { compiler } from './compiler';
4
- import type {
5
- IFinaleCompilerOptions,
6
- BabelOptions,
7
- ICompilerResult,
8
- IVirtualDist,
9
- ICompilerMessageDetail,
10
- } from './type';
11
-
12
- export const build = async (
13
- option: IFinaleCompilerOptions,
14
- babelConfig: BabelOptions = {},
15
- ): Promise<ICompilerResult> => {
16
- const {
17
- rootDir,
18
- enableVirtualDist,
19
- filenames,
20
- clean,
21
- distDir,
22
- distFileExtMap = defaultDistFileExtMap,
23
- verbose = false,
24
- quiet = false,
25
- } = option;
26
-
27
- const virtualDists: IVirtualDist[] = [];
28
-
29
- if (clean) {
30
- await fs.remove(distDir);
31
- }
32
-
33
- fs.ensureDir(distDir);
34
- const messageDetails: ICompilerMessageDetail[] = [];
35
-
36
- for (const filename of filenames) {
37
- try {
38
- const dist = compiler({
39
- rootDir,
40
- enableVirtualDist,
41
- filepath: filename,
42
- distDir,
43
- verbose,
44
- quiet,
45
- babelConfig,
46
- distFileExtMap,
47
- });
48
- if (enableVirtualDist && dist) {
49
- virtualDists.push(dist);
50
- }
51
- } catch (e: any) {
52
- messageDetails.push({
53
- filename,
54
- content: e.toString(),
55
- });
56
- }
57
- }
58
-
59
- const happenError = messageDetails.length > 0;
60
-
61
- if (!quiet) {
62
- if (happenError) {
63
- logger.error(
64
- `Compilation failure ${messageDetails.length} ${
65
- messageDetails.length !== 1 ? 'files' : 'file'
66
- } with Babel.`,
67
- );
68
- // TODO: 具体的报错信息打印
69
- } else {
70
- logger.info(
71
- `Successfully compiled ${filenames.length} ${
72
- filenames.length !== 1 ? 'files' : 'file'
73
- } with Babel.`,
74
- );
75
- }
76
- }
77
-
78
- if (happenError) {
79
- return {
80
- code: 1,
81
- message: `Compilation failure ${messageDetails.length} ${
82
- messageDetails.length !== 1 ? 'files' : 'file'
83
- } with Babel.`,
84
- messageDetails,
85
- };
86
- }
87
-
88
- return {
89
- code: 0,
90
- message: `Successfully compiled ${filenames.length} ${
91
- filenames.length !== 1 ? 'files' : 'file'
92
- } with Babel.`,
93
- virtualDists,
94
- };
95
- };
package/src/buildWatch.ts DELETED
@@ -1,113 +0,0 @@
1
- import * as path from 'path';
2
- import * as Event from 'events';
3
- import { logger, watch, WatchChangeType } from '@modern-js/utils';
4
- import { FSWatcher } from 'chokidar';
5
- import { build } from './build';
6
- import { CompilerErrorResult } from './compilerErrorResult';
7
- import type {
8
- IFinaleCompilerOptions,
9
- BabelOptions,
10
- ICompilerResult,
11
- } from './type';
12
-
13
- export const BuildWatchEvent = {
14
- firstCompiler: 'first-compiler',
15
- compiling: 'compiling',
16
- watchingCompiler: 'watching-compiler',
17
- };
18
-
19
- export class BuildWatchEmitter extends Event.EventEmitter {
20
- private _initFn!: (
21
- emitter: BuildWatchEmitter,
22
- ) => Promise<FSWatcher> | FSWatcher;
23
-
24
- setInitFn(fn: (emitter: BuildWatchEmitter) => Promise<any> | any) {
25
- this._initFn = fn;
26
- }
27
-
28
- async watch() {
29
- if (typeof this._initFn === 'function') {
30
- return this._initFn(this);
31
- }
32
-
33
- return null;
34
- }
35
- }
36
-
37
- export const runBuildWatch = async (
38
- option: IFinaleCompilerOptions,
39
- babelConfig: BabelOptions = {},
40
- emitter: BuildWatchEmitter,
41
- ) => {
42
- emitter.emit(BuildWatchEvent.compiling);
43
- const errorResult = new CompilerErrorResult();
44
- const watchDir = option.watchDir as string;
45
- const { distDir, quiet } = option;
46
- // 第一次正常构建
47
- const fisrtBuildResult = await build(option, babelConfig);
48
-
49
- const { code } = fisrtBuildResult;
50
- if (code === 1) {
51
- errorResult.init(fisrtBuildResult);
52
- emitter.emit(BuildWatchEvent.firstCompiler, errorResult.value);
53
- } else {
54
- emitter.emit(BuildWatchEvent.firstCompiler, fisrtBuildResult);
55
- }
56
-
57
- return watch(
58
- `${watchDir}/**/*.{js,jsx,ts,tsx}`,
59
- async ({ changeType, changedFilePath }) => {
60
- emitter.emit(BuildWatchEvent.compiling);
61
- if (changeType === WatchChangeType.UNLINK) {
62
- const removeFiles = [
63
- path.normalize(
64
- `./${distDir}/${path.relative(watchDir, changedFilePath)}`,
65
- ),
66
- ];
67
- if (!quiet) {
68
- logger.info(`remove file: ${removeFiles.join(',')}`);
69
- }
70
- const result: ICompilerResult = {
71
- code: 0,
72
- message: `remove file: ${removeFiles.join(',')}`,
73
- removeFiles,
74
- };
75
- emitter.emit(BuildWatchEvent.watchingCompiler, result);
76
- return;
77
- }
78
-
79
- const result = await build(
80
- { ...option, filenames: [changedFilePath] },
81
- babelConfig,
82
- );
83
- if (result.code === 1) {
84
- errorResult.update(result.messageDetails || []);
85
- emitter.emit(BuildWatchEvent.watchingCompiler, errorResult.value);
86
- !quiet && logger.info(errorResult.value.message);
87
- } else {
88
- errorResult.removeByFileName(changedFilePath);
89
- // 如果该文件没有报错,则更新该文件状态并检查是否还存在其他报错文件
90
- if (errorResult.checkExistError()) {
91
- emitter.emit(BuildWatchEvent.watchingCompiler, {
92
- ...errorResult.value,
93
- virtualDists: result.virtualDists,
94
- } as ICompilerResult);
95
- !quiet && logger.info(errorResult.value.message);
96
- } else {
97
- emitter.emit(BuildWatchEvent.watchingCompiler, result);
98
- !quiet && logger.info(result.message);
99
- }
100
- }
101
- },
102
- [`${watchDir}/**/*.d.ts`],
103
- );
104
- };
105
-
106
- export const buildWatch = (
107
- option: IFinaleCompilerOptions,
108
- babelConfig: BabelOptions = {},
109
- ) => {
110
- const buildWatchEmitter = new BuildWatchEmitter();
111
- buildWatchEmitter.setInitFn(runBuildWatch.bind(null, option, babelConfig));
112
- return buildWatchEmitter;
113
- };
package/src/compiler.ts DELETED
@@ -1,151 +0,0 @@
1
- import * as path from 'path';
2
- import * as babel from '@babel/core';
3
- import { logger, fs } from '@modern-js/utils';
4
- import * as utils from './utils';
5
- import { BabelOptions, IVirtualDist } from './type';
6
- import { defaultDistFileExtMap } from './constants';
7
-
8
- export interface ISingleFileCompilerOption {
9
- filepath: string;
10
- rootDir: string;
11
- enableVirtualDist?: boolean;
12
- distDir?: string;
13
- verbose?: boolean;
14
- quiet?: boolean;
15
- babelConfig?: BabelOptions;
16
- distFileExtMap?: Record<string, string>;
17
- }
18
-
19
- const defaultDistDir = 'dist';
20
-
21
- export const isRes = (
22
- r: babel.BabelFileResult | null,
23
- ): r is babel.BabelFileResult => Boolean(r);
24
-
25
- export const getDistFilePath = (option: {
26
- filepath: string;
27
- rootDir: string;
28
- distDir: string;
29
- extMap: Record<string, string>;
30
- }) => {
31
- const { filepath, rootDir, distDir, extMap } = option;
32
- const ext = path.extname(filepath);
33
- return path.join(
34
- distDir,
35
- path.relative(rootDir, filepath).replace(ext, extMap[ext]),
36
- );
37
- };
38
-
39
- export const resolveSourceMap = (option: {
40
- babelRes: babel.BabelFileResult;
41
- sourceFilePath: string;
42
- distFilePath: string;
43
- enableVirtualDist?: boolean;
44
- }) => {
45
- const {
46
- babelRes,
47
- sourceFilePath,
48
- distFilePath,
49
- enableVirtualDist = false,
50
- } = option;
51
- const mapLoc = `${distFilePath}.map`;
52
- babelRes.code = utils.addSourceMappingUrl(babelRes.code as string, mapLoc);
53
-
54
- if (babelRes.map) {
55
- babelRes.map.file = path.basename(distFilePath);
56
- babelRes.map.sources = [
57
- path.relative(path.dirname(distFilePath), sourceFilePath),
58
- ];
59
- }
60
-
61
- const sourceMapVirtualDist = {
62
- sourcemap: JSON.stringify(babelRes.map),
63
- sourceMapPath: mapLoc,
64
- };
65
-
66
- if (enableVirtualDist) {
67
- return sourceMapVirtualDist;
68
- }
69
-
70
- fs.ensureDirSync(path.dirname(mapLoc));
71
- fs.writeFileSync(mapLoc, JSON.stringify(babelRes.map));
72
-
73
- return sourceMapVirtualDist;
74
- };
75
-
76
- export const compiler = (option: ISingleFileCompilerOption) => {
77
- const {
78
- filepath,
79
- rootDir,
80
- enableVirtualDist = false,
81
- distDir = path.join(path.dirname(rootDir), defaultDistDir),
82
- verbose = false,
83
- babelConfig = {},
84
- distFileExtMap = defaultDistFileExtMap,
85
- quiet = false,
86
- } = option;
87
- const babelRes = babel.transformFileSync(filepath, babelConfig);
88
- let virtualDist: IVirtualDist | null = null;
89
-
90
- if (!isRes(babelRes)) {
91
- throw new Error(`${filepath} happen error`);
92
- }
93
-
94
- const distFilePath = getDistFilePath({
95
- filepath,
96
- rootDir,
97
- distDir,
98
- extMap: distFileExtMap,
99
- });
100
-
101
- if (enableVirtualDist) {
102
- virtualDist = {
103
- distPath: distFilePath,
104
- sourceMapPath: '',
105
- code: '',
106
- sourcemap: '',
107
- };
108
- }
109
-
110
- if (
111
- babelRes?.map &&
112
- babelConfig.sourceMaps &&
113
- babelConfig.sourceMaps !== 'inline'
114
- ) {
115
- if (virtualDist) {
116
- virtualDist = {
117
- ...virtualDist,
118
- ...resolveSourceMap({
119
- babelRes,
120
- sourceFilePath: filepath,
121
- distFilePath,
122
- enableVirtualDist,
123
- }),
124
- };
125
- } else {
126
- resolveSourceMap({
127
- babelRes,
128
- sourceFilePath: filepath,
129
- distFilePath,
130
- enableVirtualDist,
131
- });
132
- }
133
- }
134
-
135
- if (virtualDist) {
136
- virtualDist = {
137
- ...virtualDist,
138
- distPath: distFilePath,
139
- code: babelRes.code as string,
140
- };
141
- } else {
142
- fs.ensureDirSync(path.dirname(distFilePath));
143
- fs.writeFileSync(distFilePath, babelRes.code as string);
144
- }
145
-
146
- if (verbose && !quiet) {
147
- logger.info(`${filepath} => ${distFilePath}`);
148
- }
149
-
150
- return virtualDist;
151
- };
@@ -1,49 +0,0 @@
1
- import { ICompilerResult, ICompilerMessageDetail } from './type';
2
-
3
- export class CompilerErrorResult {
4
- _messageDetails!: ICompilerMessageDetail[];
5
-
6
- constructor(initErrorResult?: ICompilerResult) {
7
- this.init(initErrorResult);
8
- }
9
-
10
- init(initErrorResult?: ICompilerResult) {
11
- this._messageDetails = initErrorResult?.messageDetails || [];
12
- }
13
-
14
- update(messageDetails: ICompilerMessageDetail[]) {
15
- for (const messageDetail of messageDetails) {
16
- // 遍历存不存在该文件报错信息,不存在则增加,否则更新内容
17
- const addError = !this._messageDetails.some(detail => {
18
- if (detail.filename === messageDetail.filename) {
19
- // 如果错误栈里存在该文件报错信息,则更新内容
20
- detail.content = messageDetail.content;
21
- return true;
22
- }
23
- return false;
24
- });
25
-
26
- if (addError) {
27
- this._messageDetails.push(messageDetail);
28
- }
29
- }
30
- }
31
-
32
- removeByFileName(filename: string) {
33
- this._messageDetails = this._messageDetails.filter(
34
- detail => detail.filename !== filename,
35
- );
36
- }
37
-
38
- get value(): ICompilerResult {
39
- return {
40
- code: 1,
41
- message: `Compilation failure ${this._messageDetails?.length} files with Babel.`,
42
- messageDetails: this._messageDetails,
43
- };
44
- }
45
-
46
- checkExistError() {
47
- return this._messageDetails.length > 0;
48
- }
49
- }
package/src/constants.ts DELETED
@@ -1,6 +0,0 @@
1
- export const defaultDistFileExtMap = {
2
- '.js': '.js',
3
- '.jsx': '.js',
4
- '.ts': '.js',
5
- '.tsx': '.js',
6
- };
package/src/defaults.ts DELETED
@@ -1,21 +0,0 @@
1
- import { ICompilerOptions, ICompilerOptionsWithDefault } from './type';
2
- import { defaultDistFileExtMap } from './constants';
3
-
4
- const defaultOptions = {
5
- enableWatch: false,
6
- enableVirtualDist: false,
7
- extensions: [],
8
- filenames: [],
9
- distFileExtMap: defaultDistFileExtMap,
10
- ignore: [],
11
- quiet: false,
12
- verbose: false,
13
- clean: false,
14
- };
15
-
16
- export const mergeDefaultOption = (
17
- compilerOptions: ICompilerOptions,
18
- ): ICompilerOptionsWithDefault => ({
19
- ...defaultOptions,
20
- ...compilerOptions,
21
- });
@@ -1,93 +0,0 @@
1
- import * as glob from 'glob';
2
- import type { IOptions } from 'glob';
3
- import { DEFAULT_EXTENSIONS } from '@babel/core';
4
- import {
5
- Extensions,
6
- ExtensionsFunc,
7
- ICompilerOptions,
8
- IFinaleCompilerOptions,
9
- } from './type';
10
- import { mergeDefaultOption } from './defaults';
11
-
12
- export const getGlobPattern = (dir: string, extensions: Extensions) => {
13
- if (extensions.length > 1) {
14
- return `${dir}/**/*{${extensions.join(',')}}`;
15
- } else if (extensions.length === 1) {
16
- return `${dir}/**/*${extensions[0]}`;
17
- } else {
18
- return `${dir}/**/*`;
19
- }
20
- };
21
- export const getFinalExtensions = (
22
- extensions: Extensions | ExtensionsFunc | undefined,
23
- ) => {
24
- const isExtensions = (
25
- ext: Extensions | ExtensionsFunc | undefined,
26
- ): ext is Extensions => Array.isArray(ext);
27
-
28
- const isExtensionsFunc = (
29
- ext: Extensions | ExtensionsFunc | undefined,
30
- ): ext is ExtensionsFunc => typeof ext === 'function';
31
-
32
- if (isExtensions(extensions)) {
33
- return [...extensions, ...DEFAULT_EXTENSIONS];
34
- } else if (isExtensionsFunc(extensions)) {
35
- return extensions(DEFAULT_EXTENSIONS);
36
- } else {
37
- return DEFAULT_EXTENSIONS;
38
- }
39
- };
40
-
41
- export const getFilesFromDir = ({
42
- dir,
43
- finalExt = [],
44
- ignore = [],
45
- }: {
46
- dir: string;
47
- finalExt?: string[];
48
- ignore?: IOptions['ignore'];
49
- }) => {
50
- let globFindFilenames: string[] = [];
51
- const globPattern = getGlobPattern(dir, finalExt);
52
-
53
- globFindFilenames = glob.sync(globPattern, { ignore });
54
-
55
- return globFindFilenames;
56
- };
57
-
58
- export const getFinalCompilerOption = (
59
- option: ICompilerOptions,
60
- ): IFinaleCompilerOptions => {
61
- const optionWithDefault = mergeDefaultOption(option);
62
- const {
63
- sourceDir,
64
- ignore,
65
- enableWatch = false,
66
- watchDir,
67
- extensions = DEFAULT_EXTENSIONS,
68
- } = option;
69
- let globFindFilenames: string[] = [];
70
-
71
- const finalExt = getFinalExtensions(extensions);
72
- if (sourceDir) {
73
- globFindFilenames = getFilesFromDir({
74
- dir: sourceDir,
75
- ignore,
76
- finalExt,
77
- });
78
- }
79
-
80
- if (enableWatch) {
81
- // 开启watch模式,清空通过 sourceDir 找到的文件,而改为使用watchDirs
82
- globFindFilenames = getFilesFromDir({
83
- dir: watchDir as string,
84
- ignore,
85
- finalExt,
86
- });
87
- }
88
-
89
- return {
90
- ...optionWithDefault,
91
- filenames: [...optionWithDefault.filenames, ...globFindFilenames],
92
- };
93
- };
package/src/index.ts DELETED
@@ -1,35 +0,0 @@
1
- import { ICompilerOptions, ICompilerResult, BabelOptions } from './type';
2
- import { getFinalCompilerOption } from './getFinalOption';
3
- import { build } from './build';
4
- import { buildWatch, BuildWatchEmitter } from './buildWatch';
5
- import { validate } from './validate';
6
-
7
- export async function compiler(
8
- compilerOptions: ICompilerOptions & { enableWatch: true },
9
- babelOptions?: BabelOptions,
10
- ): Promise<BuildWatchEmitter>;
11
- export async function compiler(
12
- compilerOptions: ICompilerOptions & { enableWatch?: false },
13
- babelOptions?: BabelOptions,
14
- ): Promise<ICompilerResult>;
15
-
16
- export async function compiler(
17
- compilerOptions: ICompilerOptions,
18
- babelOptions: BabelOptions = {},
19
- ) {
20
- const validRet = validate(compilerOptions);
21
-
22
- if (validRet) {
23
- return validRet;
24
- }
25
- const finalCompilerOption = getFinalCompilerOption(compilerOptions);
26
-
27
- if (compilerOptions.enableWatch) {
28
- return buildWatch(finalCompilerOption, babelOptions);
29
- } else {
30
- return build(finalCompilerOption, babelOptions);
31
- }
32
- }
33
-
34
- export * from './buildWatch';
35
- export * from './type';
package/src/type.ts DELETED
@@ -1,76 +0,0 @@
1
- import { TransformOptions } from '@babel/core';
2
- import type { IOptions } from 'glob';
3
-
4
- export type BabelOptions = TransformOptions;
5
- export type Extensions = string[];
6
- export type ExtensionsFunc = (defaultExtensions: Extensions) => Extensions;
7
-
8
- export interface ICompilerOptions {
9
- rootDir: string;
10
- distDir: string;
11
- sourceDir?: string;
12
- watchDir?: string;
13
- enableWatch?: boolean;
14
- enableVirtualDist?: boolean;
15
- extensions?: Extensions | ExtensionsFunc;
16
- filenames?: string[];
17
- distFileExtMap?: Record<string, string>;
18
- ignore?: IOptions['ignore'];
19
- quiet?: boolean;
20
- verbose?: boolean;
21
- clean?: boolean;
22
- }
23
-
24
- export interface ICompilerOptionsWithDefault {
25
- rootDir: string;
26
- enableVirtualDist?: boolean;
27
- sourceDir?: string;
28
- watchDir?: string;
29
- enableWatch?: boolean;
30
- distDir: string;
31
- extensions: Extensions | ExtensionsFunc;
32
- filenames: string[];
33
- distFileExtMap?: Record<string, string>;
34
- ignore: IOptions['ignore'];
35
- quiet?: boolean;
36
- verbose?: boolean;
37
- clean?: boolean;
38
- }
39
-
40
- export interface IFinaleCompilerOptions {
41
- rootDir: string;
42
- filenames: string[];
43
- ignore?: IOptions['ignore'];
44
- enableVirtualDist?: boolean;
45
- distDir: string;
46
- watchDir?: string;
47
- enableWatch?: boolean;
48
- distFileExtMap?: Record<string, string>;
49
- quiet?: boolean;
50
- verbose?: boolean;
51
- clean?: boolean;
52
- }
53
-
54
- export interface BuildOptions {
55
- babelOptions: BabelOptions;
56
- }
57
-
58
- export interface IVirtualDist {
59
- distPath: string;
60
- sourceMapPath: string;
61
- code: string;
62
- sourcemap: string;
63
- }
64
-
65
- export interface ICompilerMessageDetail {
66
- filename: string;
67
- content: string;
68
- }
69
-
70
- export interface ICompilerResult {
71
- code: number;
72
- message: string;
73
- messageDetails?: ICompilerMessageDetail[];
74
- virtualDists?: IVirtualDist[];
75
- removeFiles?: string[];
76
- }
package/src/utils.ts DELETED
@@ -1,5 +0,0 @@
1
- import * as path from 'path';
2
-
3
- export function addSourceMappingUrl(code: string, loc: string): string {
4
- return `${code}\n//# sourceMappingURL=${path.normalize(path.basename(loc))}`;
5
- }
package/src/validate.ts DELETED
@@ -1,47 +0,0 @@
1
- import { logger } from '@modern-js/utils';
2
- import { ICompilerOptions, ICompilerResult } from './type';
3
-
4
- export const sourceDirAndFileNamesValidMessage =
5
- 'At least one of the sourceDir and filenames configurations must be configured';
6
- export const watchDirValidMessage =
7
- 'should set watchDir when enableWatch is true';
8
-
9
- export const validateSourceDirAndFileNames = (
10
- compilerOptions: ICompilerOptions,
11
- ): ICompilerResult | null => {
12
- const { sourceDir, filenames, quiet } = compilerOptions;
13
- if (!sourceDir && !filenames) {
14
- if (!quiet) {
15
- logger.error(sourceDirAndFileNamesValidMessage);
16
- }
17
- return {
18
- code: 1,
19
- message: sourceDirAndFileNamesValidMessage,
20
- virtualDists: [],
21
- };
22
- }
23
-
24
- return null;
25
- };
26
-
27
- export const validateWatchDir = (
28
- compilerOptions: ICompilerOptions,
29
- ): ICompilerResult | null => {
30
- const { watchDir, enableWatch, quiet } = compilerOptions;
31
- if (enableWatch && !watchDir) {
32
- if (!quiet) {
33
- logger.error(watchDirValidMessage);
34
- }
35
- return { code: 1, message: watchDirValidMessage, virtualDists: [] };
36
- }
37
-
38
- return null;
39
- };
40
-
41
- export const validate = (compilerOptions: ICompilerOptions) => {
42
- if (compilerOptions.enableWatch) {
43
- return validateWatchDir(compilerOptions);
44
- }
45
-
46
- return validateSourceDirAndFileNames(compilerOptions);
47
- };