UNPKG

@modern-js/module-tools-v2

Version:

The meta-framework suite designed from scratch for frontend-focused modern web development.

192 lines (180 loc) 9.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveAlias = exports.getTscBinPath = exports.generatorTsConfig = exports.assignTsConfigPath = void 0; var _path = _interopRequireDefault(require("path")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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; } 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; } 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; } 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); } 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; } const generatorTsConfig = async (projectTsconfig, config) => { var _projectTsconfig$comp, _projectTsconfig$comp2, _projectTsconfig$excl; const { fs, lodash, nanoid } = await Promise.resolve().then(() => _interopRequireWildcard(require('@modern-js/utils'))); const { dtsTempDirectory } = await Promise.resolve().then(() => _interopRequireWildcard(require("../constants/dts"))); const { appDirectory, sourceDir: absSourceDir, distAbsPath, tsconfigPath } = config; const tempDistAbsRootPath = _path.default.join(appDirectory, `${dtsTempDirectory}/${nanoid()}`); const tempDistAbsSrcPath = _path.default.join(tempDistAbsRootPath, _path.default.relative(appDirectory, absSourceDir)); const rootDir = _path.default.relative(tempDistAbsRootPath, appDirectory); const baseUrl = (_projectTsconfig$comp = projectTsconfig.compilerOptions) !== null && _projectTsconfig$comp !== void 0 && _projectTsconfig$comp.baseUrl ? _path.default.join(appDirectory, (_projectTsconfig$comp2 = projectTsconfig.compilerOptions) === null || _projectTsconfig$comp2 === void 0 ? void 0 : _projectTsconfig$comp2.baseUrl) : appDirectory; // if include = ['src'], final include should be ['../src'] const include = [_path.default.relative(tempDistAbsRootPath, absSourceDir)]; const resetConfig = { compilerOptions: _objectSpread(_objectSpread({}, projectTsconfig === null || projectTsconfig === void 0 ? void 0 : projectTsconfig.compilerOptions), {}, { rootDir, baseUrl, // Ensure that .d.ts files are created by tsc, but not .js files declaration: true, emitDeclarationOnly: true, outDir: tempDistAbsRootPath }), include, exclude: (_projectTsconfig$excl = projectTsconfig.exclude) !== null && _projectTsconfig$excl !== void 0 ? _projectTsconfig$excl : [] }; // extends: '../tsconfig.json' if (projectTsconfig.extends) { resetConfig.extends = projectTsconfig.extends.startsWith('.') ? _path.default.join(_path.default.relative(`${distAbsPath}/tsconfig.json`, tsconfigPath), projectTsconfig.extends) : projectTsconfig.extends; } const recommendOption = { // Ensure that Babel can safely transpile files in the TypeScript project compilerOptions: { isolatedModules: true } }; const tempTsconfigPath = _path.default.join(tempDistAbsRootPath, `tsconfig.json`); fs.ensureFileSync(tempTsconfigPath); const deepMerge = lodash.merge; fs.writeJSONSync(tempTsconfigPath, deepMerge(recommendOption, projectTsconfig, // 此处是必须要覆盖用户默认配置 resetConfig)); return { tempTsconfigPath, tempDistAbsRootPath, tempDistAbsSrcPath }; }; exports.generatorTsConfig = generatorTsConfig; const getTscBinPath = async appDirectory => { const { fs } = await Promise.resolve().then(() => _interopRequireWildcard(require('@modern-js/utils'))); const { default: findUp, exists: pathExists } = await Promise.resolve().then(() => _interopRequireWildcard(require("../../compiled/find-up"))); const tscBinFile = await findUp(async directory => { const targetFilePath = _path.default.join(directory, './node_modules/.bin/tsc'); const hasTscBinFile = await pathExists(targetFilePath); if (hasTscBinFile) { return targetFilePath; } return undefined; }, { cwd: appDirectory }); if (!tscBinFile || !fs.existsSync(tscBinFile)) { throw new Error('Failed to excute the `tsc` command, please check if `typescript` is installed correctly in the current directory.'); } return tscBinFile; }; exports.getTscBinPath = getTscBinPath; const resolveAlias = async (config, options, watchFilenames = []) => { var _userTsconfig$compile, _userTsconfig$compile2; const { userTsconfig, tempDistAbsSrcPath, tempDistAbsRootPath } = options; const { globby, fs } = await Promise.resolve().then(() => _interopRequireWildcard(require('@modern-js/utils'))); const { transformDtsAlias } = await Promise.resolve().then(() => _interopRequireWildcard(require("./tspaths-transform"))); const { distAbsPath } = config; const dtsDistPath = `${tempDistAbsSrcPath}/**/*.d.ts`; const dtsFilenames = watchFilenames.length > 0 ? watchFilenames : globby.sync(dtsDistPath, { absolute: true }); const result = transformDtsAlias({ filenames: dtsFilenames, baseUrl: tempDistAbsRootPath, paths: (_userTsconfig$compile = (_userTsconfig$compile2 = userTsconfig.compilerOptions) === null || _userTsconfig$compile2 === void 0 ? void 0 : _userTsconfig$compile2.paths) !== null && _userTsconfig$compile !== void 0 ? _userTsconfig$compile : {} }); for (const r of result) { fs.writeFileSync(r.path, r.content); } await fs.copy(tempDistAbsSrcPath, distAbsPath); }; // export const matchesPattern = (calleePath: NodePath, pattern: string) => { // const { node } = calleePath; // if (t.isMemberExpression(node)) { // return calleePath.matchesPattern(pattern); // } // if (!t.isIdentifier(node) || pattern.includes('.')) { // return false; // } // const name = pattern.split('.')[0]; // return node.name === name; // }; // export const isImportCall = (calleePath: NodePath<tt.CallExpression>) => { // return t.isImport(calleePath.node.callee); // }; // export const verifyTsConfigPaths = async ( // tsconfigAbsPath: string, // userAliases?: AliasOption, // ) => { // const { readTsConfigByFile, chalk } = await import('@modern-js/utils'); // if (!userAliases) { // return; // } // const paths = Object.keys( // readTsConfigByFile(tsconfigAbsPath).compilerOptions?.paths || {}, // ).map(key => key.replace(/\/\*$/, '')); // Object.keys(userAliases).forEach(name => { // if (paths.includes(name)) { // throw new Error( // chalk.red( // `It looks like you have configured the alias ${chalk.bold( // name, // )} in both the modern.config file and tsconfig.json.\n Please remove the configuration in modern.config file and just keep the configuration in tsconfig.json.`, // ), // ); // } // }); // }; exports.resolveAlias = resolveAlias; const assignTsConfigPath = async (config, options) => { const { defaultTsConfigPath } = await Promise.resolve().then(() => _interopRequireWildcard(require("../constants/dts"))); // user run `build --tsconfig './tsconfig.build.json'` if (typeof options.tsconfig === 'string' && options.tsconfig !== defaultTsConfigPath) { var _config$dts; config.dts = _objectSpread(_objectSpread({ only: false, distPath: './' }, (_config$dts = config.dts) !== null && _config$dts !== void 0 ? _config$dts : {}), {}, { tsconfigPath: options.tsconfig }); } return config; }; exports.assignTsConfigPath = assignTsConfigPath; //# sourceMappingURL=dts.js.map