@modern-js/server-utils 1.2.12-beta.0 → 1.15.1-beta.1

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 (27) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/js/modern/common/index.js +32 -0
  3. package/dist/js/modern/{babel.js → compilers/babel/index.js} +40 -11
  4. package/dist/js/modern/compilers/typescript/index.js +101 -0
  5. package/dist/js/modern/compilers/typescript/tsconfig-paths-plugin.js +138 -0
  6. package/dist/js/modern/compilers/typescript/typescript-loader.js +32 -0
  7. package/dist/js/modern/index.js +2 -1
  8. package/dist/js/node/common/index.js +50 -0
  9. package/dist/js/node/{babel.js → compilers/babel/index.js} +54 -14
  10. package/dist/js/node/compilers/typescript/index.js +123 -0
  11. package/dist/js/node/compilers/typescript/tsconfig-paths-plugin.js +152 -0
  12. package/dist/js/node/compilers/typescript/typescript-loader.js +41 -0
  13. package/dist/js/node/index.js +14 -2
  14. package/dist/js/treeshaking/common/index.js +76 -0
  15. package/dist/js/treeshaking/compilers/babel/index.js +159 -0
  16. package/dist/js/treeshaking/compilers/typescript/index.js +176 -0
  17. package/dist/js/treeshaking/compilers/typescript/tsconfig-paths-plugin.js +155 -0
  18. package/dist/js/treeshaking/compilers/typescript/typescript-loader.js +39 -0
  19. package/dist/js/treeshaking/index.js +2 -1
  20. package/dist/types/common/index.d.ts +14 -0
  21. package/dist/types/{babel.d.ts → compilers/babel/index.d.ts} +3 -1
  22. package/dist/types/compilers/typescript/index.d.ts +2 -0
  23. package/dist/types/compilers/typescript/tsconfig-paths-plugin.d.ts +2 -0
  24. package/dist/types/compilers/typescript/typescript-loader.d.ts +11 -0
  25. package/dist/types/index.d.ts +2 -1
  26. package/package.json +13 -8
  27. package/dist/js/treeshaking/babel.js +0 -82
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @modern-js/server-utils
2
2
 
3
+ ## 1.15.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [8658a78]
8
+ - Updated dependencies [05d4a4f]
9
+ - Updated dependencies [ad05af9]
10
+ - Updated dependencies [5d53d1c]
11
+ - Updated dependencies [37cd159]
12
+ - @modern-js/utils@1.15.0
13
+ - @modern-js/babel-preset-lib@1.15.0
14
+ - @modern-js/plugin@1.15.0
15
+
3
16
  ## 1.2.11
4
17
 
5
18
  ### Patch Changes
@@ -0,0 +1,32 @@
1
+ import * as path from 'path';
2
+ import { fs } from '@modern-js/utils';
3
+ import { compileByTs } from "../compilers/typescript";
4
+ import { compileByBabel } from "../compilers/babel";
5
+ export const FILE_EXTENSIONS = ['.js', '.ts', '.mjs', '.ejs'];
6
+
7
+ const validateAbsolutePath = (filename, message) => {
8
+ if (!path.isAbsolute(filename)) {
9
+ throw new Error(message);
10
+ }
11
+ };
12
+
13
+ const validateAbsolutePaths = (filenames, messageFunc) => {
14
+ filenames.forEach(filename => validateAbsolutePath(filename, messageFunc(filename)));
15
+ };
16
+
17
+ export const compile = async (appDirectory, modernConfig, compileOptions) => {
18
+ const {
19
+ sourceDirs,
20
+ distDir,
21
+ tsconfigPath
22
+ } = compileOptions;
23
+ validateAbsolutePaths(sourceDirs, dir => `source dir ${dir} is not an absolute path.`);
24
+ validateAbsolutePath(distDir, `dist dir ${distDir} is not an absolute path.`);
25
+ const isTsProject = tsconfigPath && (await fs.pathExists(tsconfigPath));
26
+
27
+ if (isTsProject) {
28
+ await compileByTs(appDirectory, modernConfig, compileOptions);
29
+ } else {
30
+ await compileByBabel(appDirectory, modernConfig, compileOptions);
31
+ }
32
+ };
@@ -4,8 +4,11 @@ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { va
4
4
 
5
5
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
6
 
7
+ import * as path from 'path';
7
8
  import { getBabelChain, applyUserBabelConfig } from '@modern-js/babel-preset-lib';
8
9
  import { fs, json5, getAlias, applyOptionsChain } from '@modern-js/utils';
10
+ import { compiler } from '@modern-js/babel-compiler';
11
+ import { FILE_EXTENSIONS } from "../../common";
9
12
  export * from '@babel/core';
10
13
  export const readTsConfig = (tsconfigPath, noExistReturn = null) => {
11
14
  // 如果不存在,则返回 noExistReturn
@@ -65,27 +68,53 @@ export const resolveBabelConfig = (appDirectory, modernConfig, option // FIXME:
65
68
  });
66
69
  const envOptions = babelChain.preset('@babel/preset-env').options();
67
70
  babelChain.preset('@babel/preset-env').use(require.resolve('@babel/preset-env'), [_objectSpread(_objectSpread({}, envOptions[0]), {}, {
68
- targets: {
69
- node: '12.18.3'
70
- },
71
71
  loose: true
72
72
  })]);
73
73
  babelChain.plugin('babel-plugin-transform-typescript-metadata').use(require.resolve('babel-plugin-transform-typescript-metadata'), []);
74
74
  babelChain.plugin('@babel/plugin-proposal-decorators').use(require.resolve('@babel/plugin-proposal-decorators'), [{
75
75
  legacy: true
76
76
  }]); // resolve "Definitely assigned fields cannot be initialized here, but only in the constructor."
77
- // babelChain
78
- // .plugin('@babel/plugin-proposal-class-properties')
79
- // .use(require.resolve('@babel/plugin-proposal-class-properties'), [
80
- // {
81
- // loose: true,
82
- // },
83
- // ]);
84
77
 
85
- babelChain.plugin('@babel/plugin-syntax-class-properties').use(require.resolve('@babel/plugin-syntax-class-properties'), []);
78
+ babelChain.plugin('@babel/plugin-proposal-class-properties').use(require.resolve('@babel/plugin-proposal-class-properties'), [{
79
+ loose: true
80
+ }]);
86
81
 
87
82
  const internalBabelConfig = _objectSpread({}, babelChain.toJSON());
88
83
 
89
84
  const userBabelConfig = modernConfig.tools.babel;
90
85
  return applyUserBabelConfig(internalBabelConfig, userBabelConfig);
86
+ };
87
+ export const compileByBabel = async (appDirectory, modernConfig, compileOptions) => {
88
+ const {
89
+ sourceDirs,
90
+ distDir,
91
+ tsconfigPath
92
+ } = compileOptions;
93
+ const results = await Promise.all(sourceDirs.map(async sourceDir => {
94
+ const babelConfig = resolveBabelConfig(appDirectory, modernConfig, {
95
+ tsconfigPath: tsconfigPath ? tsconfigPath : '',
96
+ syntax: 'es6+',
97
+ type: 'commonjs'
98
+ });
99
+
100
+ if (await fs.pathExists(sourceDir)) {
101
+ const basename = path.basename(sourceDir);
102
+ const targetDir = path.join(distDir, basename);
103
+ await fs.copy(sourceDir, targetDir, {
104
+ filter: src => !['.ts', '.js'].includes(path.extname(src)) && src !== tsconfigPath
105
+ });
106
+ }
107
+
108
+ return compiler({
109
+ rootDir: appDirectory,
110
+ distDir: distDir,
111
+ sourceDir: sourceDir,
112
+ extensions: FILE_EXTENSIONS
113
+ }, babelConfig);
114
+ }));
115
+ results.forEach(result => {
116
+ if (result.code === 1) {
117
+ throw new Error(result.message);
118
+ }
119
+ });
91
120
  };
@@ -0,0 +1,101 @@
1
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
+
3
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
+
5
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+
7
+ import path from 'path';
8
+ import { logger, getAlias, fs } from '@modern-js/utils';
9
+ import { TypescriptLoader } from "./typescript-loader";
10
+ import { tsconfigPathsBeforeHookFactory } from "./tsconfig-paths-plugin";
11
+ import ts from 'typescript';
12
+
13
+ const readTsConfigByFile = tsConfigFile => {
14
+ const parsedCmd = ts.getParsedCommandLineOfConfigFile(tsConfigFile, undefined, ts.sys);
15
+ const {
16
+ options,
17
+ fileNames,
18
+ projectReferences
19
+ } = parsedCmd;
20
+ return {
21
+ options,
22
+ fileNames,
23
+ projectReferences
24
+ };
25
+ };
26
+
27
+ const copyFiles = async (from, to, tsconfigPath) => {
28
+ if (await fs.pathExists(from)) {
29
+ const basename = path.basename(from);
30
+ const targetDir = path.join(to, basename);
31
+ await fs.copy(from, targetDir, {
32
+ filter: src => !['.ts'].includes(path.extname(src)) && src !== tsconfigPath
33
+ });
34
+ }
35
+ };
36
+
37
+ export const compileByTs = async (appDirectory, modernConfig, compileOptions) => {
38
+ logger.info(`Running ts compile...`);
39
+ const {
40
+ sourceDirs,
41
+ distDir,
42
+ tsconfigPath
43
+ } = compileOptions;
44
+ if (!tsconfigPath) return;
45
+ const ts = new TypescriptLoader({
46
+ appDirectory
47
+ }).load();
48
+ const createProgram = ts.createIncrementalProgram || ts.createProgram;
49
+ const formatHost = getFormatHost(ts);
50
+ const {
51
+ alias
52
+ } = modernConfig.source;
53
+ const aliasOption = getAlias(alias || {}, {
54
+ appDirectory,
55
+ tsconfigPath
56
+ });
57
+ const {
58
+ paths = {},
59
+ absoluteBaseUrl = './'
60
+ } = aliasOption;
61
+ const {
62
+ options,
63
+ fileNames,
64
+ projectReferences
65
+ } = readTsConfigByFile(tsconfigPath);
66
+ const rootNames = fileNames.filter(fileName => {
67
+ return fileName.endsWith('.d.ts') || sourceDirs.some(sourceDir => {
68
+ return fileName.includes(sourceDir);
69
+ });
70
+ });
71
+ const targetDir = path.join(appDirectory, './dist');
72
+ let program = createProgram.call(ts, {
73
+ rootNames: rootNames,
74
+ projectReferences,
75
+ options: _objectSpread(_objectSpread({}, options), {}, {
76
+ outDir: targetDir
77
+ })
78
+ });
79
+ const tsconfigPathsPlugin = tsconfigPathsBeforeHookFactory(ts, absoluteBaseUrl, paths);
80
+ const emitResult = program.emit(undefined, undefined, undefined, undefined, {
81
+ before: [tsconfigPathsPlugin]
82
+ });
83
+ const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
84
+
85
+ if (allDiagnostics.length > 0) {
86
+ logger.error(ts.formatDiagnosticsWithColorAndContext(allDiagnostics, formatHost));
87
+ process.exit(1);
88
+ }
89
+
90
+ for (const source of sourceDirs) {
91
+ await copyFiles(source, distDir, tsconfigPath);
92
+ }
93
+ };
94
+
95
+ const getFormatHost = ts => {
96
+ return {
97
+ getCanonicalFileName: path => path,
98
+ getCurrentDirectory: ts.sys.getCurrentDirectory,
99
+ getNewLine: () => ts.sys.newLine
100
+ };
101
+ };
@@ -0,0 +1,138 @@
1
+ import * as os from 'os';
2
+ import path, { dirname, posix } from 'path';
3
+ import { createMatchPath } from 'tsconfig-paths';
4
+
5
+ const isRegExpKey = str => {
6
+ return str.startsWith('^') || str.endsWith('$');
7
+ };
8
+
9
+ const resolveAliasPath = (baseUrl, filePath) => {
10
+ if (path.isAbsolute(filePath)) {
11
+ return filePath;
12
+ }
13
+
14
+ return path.resolve(baseUrl, filePath);
15
+ };
16
+
17
+ const createAliasMatcher = (baseUrl, alias) => {
18
+ const aliasPairs = Object.keys(alias).reduce((o, key) => {
19
+ if (isRegExpKey(key)) {
20
+ const regexp = new RegExp(key);
21
+ const aliasPath = resolveAliasPath(baseUrl, alias[key]);
22
+ o.push([regexp, aliasPath]);
23
+ } else {
24
+ const aliasPath = resolveAliasPath(baseUrl, alias[key]);
25
+ o.push([key, aliasPath]);
26
+ }
27
+
28
+ return o;
29
+ }, []);
30
+ return requestedModule => {
31
+ for (const [key, value] of aliasPairs) {
32
+ if (key instanceof RegExp) {
33
+ if (key.test(requestedModule)) {
34
+ return value;
35
+ }
36
+ }
37
+
38
+ if (requestedModule === key) {
39
+ return value;
40
+ }
41
+ }
42
+ };
43
+ };
44
+
45
+ export function tsconfigPathsBeforeHookFactory(tsBinary, baseUrl, paths) {
46
+ const tsPaths = {};
47
+ const alias = {};
48
+ Object.keys(paths).forEach(key => {
49
+ if (Array.isArray(paths[key])) {
50
+ tsPaths[key] = paths[key];
51
+ } else {
52
+ alias[key] = paths[key];
53
+ }
54
+ });
55
+ const matchAliasPath = createAliasMatcher(baseUrl, alias);
56
+ const matchTsPath = createMatchPath(baseUrl, tsPaths, ['main']);
57
+
58
+ const matchPath = (requestedModule, readJSONSync, fileExists, extensions) => {
59
+ const result = matchTsPath(requestedModule, readJSONSync, fileExists, extensions);
60
+
61
+ if (result) {
62
+ return result;
63
+ }
64
+
65
+ return matchAliasPath(requestedModule);
66
+ };
67
+
68
+ if (Object.keys(paths).length === 0) {
69
+ return undefined;
70
+ }
71
+
72
+ return ctx => {
73
+ return sf => {
74
+ const visitNode = node => {
75
+ if (tsBinary.isImportDeclaration(node) || tsBinary.isExportDeclaration(node) && node.moduleSpecifier) {
76
+ try {
77
+ const importPathWithQuotes = node.moduleSpecifier && node.moduleSpecifier.getText();
78
+
79
+ if (!importPathWithQuotes) {
80
+ return node;
81
+ }
82
+
83
+ const text = importPathWithQuotes.substring(1, importPathWithQuotes.length - 1);
84
+ const result = getNotAliasedPath(sf, matchPath, text);
85
+
86
+ if (!result) {
87
+ return node;
88
+ }
89
+
90
+ const moduleSpecifier = tsBinary.factory.createStringLiteral(result);
91
+ moduleSpecifier.parent = node.moduleSpecifier.parent;
92
+
93
+ if (tsBinary.isImportDeclaration(node)) {
94
+ return tsBinary.factory.updateImportDeclaration(node, node.decorators, node.modifiers, node.importClause, moduleSpecifier, node.assertClause);
95
+ } else {
96
+ return tsBinary.factory.updateExportDeclaration(node, node.decorators, node.modifiers, node.isTypeOnly, node.exportClause, moduleSpecifier, node.assertClause);
97
+ }
98
+ } catch (_unused) {
99
+ return node;
100
+ }
101
+ }
102
+
103
+ return tsBinary.visitEachChild(node, visitNode, ctx);
104
+ };
105
+
106
+ return tsBinary.visitNode(sf, visitNode);
107
+ };
108
+ };
109
+ } // fork from https://github.com/nestjs/nest-cli/blob/HEAD/lib/compiler/hooks/tsconfig-paths.hook.ts
110
+
111
+ function getNotAliasedPath(sf, matcher, text) {
112
+ let result = matcher(text, undefined, undefined, ['.ts', '.tsx', '.js', '.jsx']);
113
+
114
+ if (!result) {
115
+ return;
116
+ }
117
+
118
+ if (os.platform() === 'win32') {
119
+ result = result.replace(/\\/g, '/');
120
+ }
121
+
122
+ if (!path.isAbsolute(result)) {
123
+ try {
124
+ // Installed packages (node modules) should take precedence over root files with the same name.
125
+ // Ref: https://github.com/nestjs/nest-cli/issues/838
126
+ const packagePath = require.resolve(text, {
127
+ paths: [process.cwd(), ...module.paths]
128
+ });
129
+
130
+ if (packagePath) {
131
+ return text;
132
+ }
133
+ } catch (_unused2) {}
134
+ }
135
+
136
+ const resolvedPath = posix.relative(dirname(sf.fileName), result) || './';
137
+ return resolvedPath[0] === '.' ? resolvedPath : './' + resolvedPath;
138
+ }
@@ -0,0 +1,32 @@
1
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2
+
3
+ export class TypescriptLoader {
4
+ constructor({
5
+ appDirectory
6
+ }) {
7
+ _defineProperty(this, "tsBinary", void 0);
8
+
9
+ _defineProperty(this, "appDirectory", void 0);
10
+
11
+ this.appDirectory = appDirectory;
12
+ }
13
+
14
+ load() {
15
+ if (this.tsBinary) {
16
+ return this.tsBinary;
17
+ }
18
+
19
+ try {
20
+ const tsPath = require.resolve('typescript', {
21
+ paths: [this.appDirectory || process.cwd()]
22
+ });
23
+
24
+ const ts = require(tsPath);
25
+
26
+ return ts;
27
+ } catch (error) {
28
+ throw new Error('TypeScript could not be found! Please, install "typescript" package.');
29
+ }
30
+ }
31
+
32
+ }
@@ -1 +1,2 @@
1
- export * from "./babel";
1
+ export * from "./compilers/babel";
2
+ export { compile } from "./common";
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.compile = exports.FILE_EXTENSIONS = void 0;
7
+
8
+ var path = _interopRequireWildcard(require("path"));
9
+
10
+ var _utils = require("@modern-js/utils");
11
+
12
+ var _typescript = require("../compilers/typescript");
13
+
14
+ var _babel = require("../compilers/babel");
15
+
16
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
17
+
18
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
19
+
20
+ const FILE_EXTENSIONS = ['.js', '.ts', '.mjs', '.ejs'];
21
+ exports.FILE_EXTENSIONS = FILE_EXTENSIONS;
22
+
23
+ const validateAbsolutePath = (filename, message) => {
24
+ if (!path.isAbsolute(filename)) {
25
+ throw new Error(message);
26
+ }
27
+ };
28
+
29
+ const validateAbsolutePaths = (filenames, messageFunc) => {
30
+ filenames.forEach(filename => validateAbsolutePath(filename, messageFunc(filename)));
31
+ };
32
+
33
+ const compile = async (appDirectory, modernConfig, compileOptions) => {
34
+ const {
35
+ sourceDirs,
36
+ distDir,
37
+ tsconfigPath
38
+ } = compileOptions;
39
+ validateAbsolutePaths(sourceDirs, dir => `source dir ${dir} is not an absolute path.`);
40
+ validateAbsolutePath(distDir, `dist dir ${distDir} is not an absolute path.`);
41
+ const isTsProject = tsconfigPath && (await _utils.fs.pathExists(tsconfigPath));
42
+
43
+ if (isTsProject) {
44
+ await (0, _typescript.compileByTs)(appDirectory, modernConfig, compileOptions);
45
+ } else {
46
+ await (0, _babel.compileByBabel)(appDirectory, modernConfig, compileOptions);
47
+ }
48
+ };
49
+
50
+ exports.compile = compile;
@@ -7,14 +7,21 @@ var _exportNames = {
7
7
  readTsConfig: true,
8
8
  existTsConfigFile: true,
9
9
  getBabelConfig: true,
10
- resolveBabelConfig: true
10
+ resolveBabelConfig: true,
11
+ compileByBabel: true
11
12
  };
12
- exports.resolveBabelConfig = exports.readTsConfig = exports.getBabelConfig = exports.existTsConfigFile = void 0;
13
+ exports.resolveBabelConfig = exports.readTsConfig = exports.getBabelConfig = exports.existTsConfigFile = exports.compileByBabel = void 0;
14
+
15
+ var path = _interopRequireWildcard(require("path"));
13
16
 
14
17
  var _babelPresetLib = require("@modern-js/babel-preset-lib");
15
18
 
16
19
  var _utils = require("@modern-js/utils");
17
20
 
21
+ var _babelCompiler = require("@modern-js/babel-compiler");
22
+
23
+ var _common = require("../../common");
24
+
18
25
  var _core = require("@babel/core");
19
26
 
20
27
  Object.keys(_core).forEach(function (key) {
@@ -29,6 +36,10 @@ Object.keys(_core).forEach(function (key) {
29
36
  });
30
37
  });
31
38
 
39
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
40
+
41
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
42
+
32
43
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
33
44
 
34
45
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
@@ -103,24 +114,16 @@ const resolveBabelConfig = (appDirectory, modernConfig, option // FIXME: babel t
103
114
  });
104
115
  const envOptions = babelChain.preset('@babel/preset-env').options();
105
116
  babelChain.preset('@babel/preset-env').use(require.resolve('@babel/preset-env'), [_objectSpread(_objectSpread({}, envOptions[0]), {}, {
106
- targets: {
107
- node: '12.18.3'
108
- },
109
117
  loose: true
110
118
  })]);
111
119
  babelChain.plugin('babel-plugin-transform-typescript-metadata').use(require.resolve('babel-plugin-transform-typescript-metadata'), []);
112
120
  babelChain.plugin('@babel/plugin-proposal-decorators').use(require.resolve('@babel/plugin-proposal-decorators'), [{
113
121
  legacy: true
114
122
  }]); // resolve "Definitely assigned fields cannot be initialized here, but only in the constructor."
115
- // babelChain
116
- // .plugin('@babel/plugin-proposal-class-properties')
117
- // .use(require.resolve('@babel/plugin-proposal-class-properties'), [
118
- // {
119
- // loose: true,
120
- // },
121
- // ]);
122
123
 
123
- babelChain.plugin('@babel/plugin-syntax-class-properties').use(require.resolve('@babel/plugin-syntax-class-properties'), []);
124
+ babelChain.plugin('@babel/plugin-proposal-class-properties').use(require.resolve('@babel/plugin-proposal-class-properties'), [{
125
+ loose: true
126
+ }]);
124
127
 
125
128
  const internalBabelConfig = _objectSpread({}, babelChain.toJSON());
126
129
 
@@ -128,4 +131,41 @@ const resolveBabelConfig = (appDirectory, modernConfig, option // FIXME: babel t
128
131
  return (0, _babelPresetLib.applyUserBabelConfig)(internalBabelConfig, userBabelConfig);
129
132
  };
130
133
 
131
- exports.resolveBabelConfig = resolveBabelConfig;
134
+ exports.resolveBabelConfig = resolveBabelConfig;
135
+
136
+ const compileByBabel = async (appDirectory, modernConfig, compileOptions) => {
137
+ const {
138
+ sourceDirs,
139
+ distDir,
140
+ tsconfigPath
141
+ } = compileOptions;
142
+ const results = await Promise.all(sourceDirs.map(async sourceDir => {
143
+ const babelConfig = resolveBabelConfig(appDirectory, modernConfig, {
144
+ tsconfigPath: tsconfigPath ? tsconfigPath : '',
145
+ syntax: 'es6+',
146
+ type: 'commonjs'
147
+ });
148
+
149
+ if (await _utils.fs.pathExists(sourceDir)) {
150
+ const basename = path.basename(sourceDir);
151
+ const targetDir = path.join(distDir, basename);
152
+ await _utils.fs.copy(sourceDir, targetDir, {
153
+ filter: src => !['.ts', '.js'].includes(path.extname(src)) && src !== tsconfigPath
154
+ });
155
+ }
156
+
157
+ return (0, _babelCompiler.compiler)({
158
+ rootDir: appDirectory,
159
+ distDir: distDir,
160
+ sourceDir: sourceDir,
161
+ extensions: _common.FILE_EXTENSIONS
162
+ }, babelConfig);
163
+ }));
164
+ results.forEach(result => {
165
+ if (result.code === 1) {
166
+ throw new Error(result.message);
167
+ }
168
+ });
169
+ };
170
+
171
+ exports.compileByBabel = compileByBabel;
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.compileByTs = void 0;
7
+
8
+ var _path = _interopRequireDefault(require("path"));
9
+
10
+ var _utils = require("@modern-js/utils");
11
+
12
+ var _typescriptLoader = require("./typescript-loader");
13
+
14
+ var _tsconfigPathsPlugin = require("./tsconfig-paths-plugin");
15
+
16
+ var _typescript = _interopRequireDefault(require("typescript"));
17
+
18
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
+
20
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
21
+
22
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
23
+
24
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
25
+
26
+ const readTsConfigByFile = tsConfigFile => {
27
+ const parsedCmd = _typescript.default.getParsedCommandLineOfConfigFile(tsConfigFile, undefined, _typescript.default.sys);
28
+
29
+ const {
30
+ options,
31
+ fileNames,
32
+ projectReferences
33
+ } = parsedCmd;
34
+ return {
35
+ options,
36
+ fileNames,
37
+ projectReferences
38
+ };
39
+ };
40
+
41
+ const copyFiles = async (from, to, tsconfigPath) => {
42
+ if (await _utils.fs.pathExists(from)) {
43
+ const basename = _path.default.basename(from);
44
+
45
+ const targetDir = _path.default.join(to, basename);
46
+
47
+ await _utils.fs.copy(from, targetDir, {
48
+ filter: src => !['.ts'].includes(_path.default.extname(src)) && src !== tsconfigPath
49
+ });
50
+ }
51
+ };
52
+
53
+ const compileByTs = async (appDirectory, modernConfig, compileOptions) => {
54
+ _utils.logger.info(`Running ts compile...`);
55
+
56
+ const {
57
+ sourceDirs,
58
+ distDir,
59
+ tsconfigPath
60
+ } = compileOptions;
61
+ if (!tsconfigPath) return;
62
+ const ts = new _typescriptLoader.TypescriptLoader({
63
+ appDirectory
64
+ }).load();
65
+ const createProgram = ts.createIncrementalProgram || ts.createProgram;
66
+ const formatHost = getFormatHost(ts);
67
+ const {
68
+ alias
69
+ } = modernConfig.source;
70
+ const aliasOption = (0, _utils.getAlias)(alias || {}, {
71
+ appDirectory,
72
+ tsconfigPath
73
+ });
74
+ const {
75
+ paths = {},
76
+ absoluteBaseUrl = './'
77
+ } = aliasOption;
78
+ const {
79
+ options,
80
+ fileNames,
81
+ projectReferences
82
+ } = readTsConfigByFile(tsconfigPath);
83
+ const rootNames = fileNames.filter(fileName => {
84
+ return fileName.endsWith('.d.ts') || sourceDirs.some(sourceDir => {
85
+ return fileName.includes(sourceDir);
86
+ });
87
+ });
88
+
89
+ const targetDir = _path.default.join(appDirectory, './dist');
90
+
91
+ let program = createProgram.call(ts, {
92
+ rootNames: rootNames,
93
+ projectReferences,
94
+ options: _objectSpread(_objectSpread({}, options), {}, {
95
+ outDir: targetDir
96
+ })
97
+ });
98
+ const tsconfigPathsPlugin = (0, _tsconfigPathsPlugin.tsconfigPathsBeforeHookFactory)(ts, absoluteBaseUrl, paths);
99
+ const emitResult = program.emit(undefined, undefined, undefined, undefined, {
100
+ before: [tsconfigPathsPlugin]
101
+ });
102
+ const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
103
+
104
+ if (allDiagnostics.length > 0) {
105
+ _utils.logger.error(ts.formatDiagnosticsWithColorAndContext(allDiagnostics, formatHost));
106
+
107
+ process.exit(1);
108
+ }
109
+
110
+ for (const source of sourceDirs) {
111
+ await copyFiles(source, distDir, tsconfigPath);
112
+ }
113
+ };
114
+
115
+ exports.compileByTs = compileByTs;
116
+
117
+ const getFormatHost = ts => {
118
+ return {
119
+ getCanonicalFileName: path => path,
120
+ getCurrentDirectory: ts.sys.getCurrentDirectory,
121
+ getNewLine: () => ts.sys.newLine
122
+ };
123
+ };