Skip to content

Commit

Permalink
refactor: core包迁移至ESM (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
otakustay committed Jan 18, 2022
1 parent ba096b2 commit 1f1fcfb
Show file tree
Hide file tree
Showing 23 changed files with 128 additions and 38 deletions.
4 changes: 1 addition & 3 deletions packages/cli-babel/src/index.ts
@@ -1,5 +1,6 @@
import path from 'path';
import {promises as fs} from 'fs';
import {globby} from 'globby';
import pLimit from 'p-limit';
import {highlight} from 'cli-highlight';
import babel, {TransformOptions} from '@babel/core';
Expand Down Expand Up @@ -46,7 +47,6 @@ const transformFile = async (file: string, baseIn: string, baseOut: string, opti
};

const transformDirectory = async (dir: string, out: string, options: TransformOptions) => {
const {globby} = await import('globby');
const files = await globby(`${dir.replace(/\/$/, '')}/**/*.{js,jsx,ts,tsx}`);
await Promise.all(files.map(f => transformFile(f, dir, out, options)));
};
Expand All @@ -69,8 +69,6 @@ const printInConsole = (code: string | null | undefined) => {
};

export const run = async (cmd: BabelCommandLineArgs, file: string): Promise<void> => {
const {globby} = await import('globby');

if (!file) {
return;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cli-dev/src/utils.ts
@@ -1,11 +1,11 @@
import WebpackDevServer from 'webpack-dev-server';
import {internalIpV4} from 'internal-ip';
import {readProjectSettings, BuildEnv, strictCheckRequiredDependency} from '@reskript/settings';
import {BuildContext, collectEntries, createRuntimeBuildEnv, EntryLocation} from '@reskript/config-webpack';
import {logger, readPackageConfig} from '@reskript/core';
import {DevCommandLineArgs} from './interface.js';

export const resolveHost = async (hostType: DevCommandLineArgs['host']) => {
const {internalIpV4} = await import('internal-ip');

if (!hostType) {
return 'localhost';
Expand Down
2 changes: 1 addition & 1 deletion packages/cli-lint/src/index.ts
@@ -1,5 +1,6 @@
import eslintPrettyFormatter from 'eslint-formatter-pretty';
import {Linter, ESLint} from 'eslint';
import {execa} from 'execa';
import {logger, gitStatus, findGitRoot} from '@reskript/core';
import {LintCommandLineArgs, ResolveOptions} from './interface.js';
import lintScripts from './script.js';
Expand All @@ -24,7 +25,6 @@ const filterUnwantedReports = (report: LintResult[], cmd: LintCommandLineArgs):
};

export const run = async (cmd: LintCommandLineArgs, files: string[]): Promise<void> => {
const {execa} = await import('execa');
const gitRoot = await findGitRoot() || process.cwd();
const status = await gitStatus(process.cwd());
const options: ResolveOptions = {...cmd, gitRoot, gitStatus: status};
Expand Down
2 changes: 1 addition & 1 deletion packages/cli-lint/src/utils.ts
@@ -1,4 +1,5 @@
import path from 'path';
import {globby} from 'globby';
import {findGitRoot} from '@reskript/core';
import {ResolveOptions} from './interface.js';

Expand All @@ -14,7 +15,6 @@ export const resolveLintFiles = async (
files: string[],
{staged, changed, gitStatus}: ResolveOptions
): Promise<string[]> => {
const {globby} = await import('globby');
const extensions = TYPE_TO_EXTENSIONS[type];

if (staged || changed) {
Expand Down
3 changes: 1 addition & 2 deletions packages/cli-play/src/utils/host.ts
@@ -1,8 +1,7 @@
import {internalIpV4} from 'internal-ip';
import {PlayCommandLineArgs} from '../interface.js';

export const resolveHost = async (hostType: PlayCommandLineArgs['host']) => {
const {internalIpV4} = await import('internal-ip');

if (!hostType) {
return 'localhost';
}
Expand Down
13 changes: 2 additions & 11 deletions packages/cli/src/DynamicImportCommand.ts
Expand Up @@ -2,10 +2,11 @@ import path from 'path';
import {existsSync} from 'fs';
import childProcess from 'child_process';
import {promisify} from 'util';
import {packageDirectory} from 'pkg-dir';
import enquirer from 'enquirer';
// @ts-expect-error
import {Command} from 'clipanion';
import type {CommandDefinition} from '@reskript/core';
import {CommandDefinition, findGitRoot, logger, readPackageConfig, resolveFrom} from '@reskript/core';

const isErrorWithCode = (error: any): error is NodeJS.ErrnoException => {
return 'message' in error && 'code' in error;
Expand All @@ -27,8 +28,6 @@ export default abstract class DynamicImportCommand<A> extends Command {
protected readonly packageName: string = '';

async execute() {
const {logger} = await import('@reskript/core');

if (!this.packageName) {
logger.error('No command package defined');
process.exit(11);
Expand All @@ -52,7 +51,6 @@ export default abstract class DynamicImportCommand<A> extends Command {
}

private async importCommandPackage() {
const {logger, resolveFrom} = await import('@reskript/core');
const resolve = resolveFrom(process.cwd());

const dynamicImport = async () => {
Expand Down Expand Up @@ -111,9 +109,6 @@ export default abstract class DynamicImportCommand<A> extends Command {
}

private async canAutoInstall() {
const {readPackageConfig} = await import('@reskript/core');
const {packageDirectory} = await import('pkg-dir');

const packageRoot = await packageDirectory();

if (!packageRoot) {
Expand All @@ -128,8 +123,6 @@ export default abstract class DynamicImportCommand<A> extends Command {
}

private async detectPackageManager(): Promise<PackageManager | null> {
const {findGitRoot} = await import('@reskript/core');

const gitRoot = await findGitRoot();

if (!gitRoot) {
Expand All @@ -150,8 +143,6 @@ export default abstract class DynamicImportCommand<A> extends Command {
}

private async installCommandPackage(): Promise<InstallReuslt> {
const {logger} = await import('@reskript/core');

const question = {
type: 'confirm',
name: 'ok',
Expand Down
1 change: 1 addition & 0 deletions packages/config-jest/src/interface.ts
@@ -1,3 +1,4 @@
// @ts-expect-error
import type {ProjectAware} from '@reskript/core';
// @ts-expect-error
import type {FeatureMatrix} from '@reskript/settings';
Expand Down
2 changes: 1 addition & 1 deletion packages/config-lint/src/rules/eslint.ts
@@ -1,4 +1,4 @@
import {resolveSync} from '@reskript/core';
import {resolveSync} from '@reskript/core/willBreakingInternalUseOnly';
import {getParseOnlyBabelConfig} from '@reskript/config-babel/willBreakingInternalUseOnly';

// 为了支持 IDE 和代码编辑工具使用 eslint 的配置,在 build 阶段会生成一份 .eslintrc 文件。参阅 scripts/post-build.js
Expand Down
2 changes: 1 addition & 1 deletion packages/config-lint/src/rules/stylelint.ts
@@ -1,4 +1,4 @@
import {resolveSync} from '@reskript/core';
import {resolveSync} from '@reskript/core/willBreakingInternalUseOnly';
import lessSyntax from 'postcss-less';

const config: Record<string, any> = {
Expand Down
2 changes: 1 addition & 1 deletion packages/config-webpack/src/partials/production.ts
@@ -1,10 +1,10 @@
import path from 'path';
import {Configuration} from 'webpack';
import {findUp} from 'find-up';
import {filter} from 'ramda';
import {ConfigurationFactory} from '../interface.js';

const factory: ConfigurationFactory = async entry => {
const {findUp} = await import('find-up');
const {cwd} = entry;
const nodeModule = async (...segments: string[]): Promise<string> => {
const name = path.join('node_modules', ...segments);
Expand Down
10 changes: 7 additions & 3 deletions packages/core/package.json
Expand Up @@ -2,11 +2,12 @@
"name": "@reskript/core",
"version": "3.0.2",
"license": "MIT",
"type": "commonjs",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": "./dist/index.js"
".": "./dist/index.js",
"./willBreakingInternalUseOnly": "./dist/internal.cjs"
},
"engines": {
"node": ">=14.18.0"
Expand All @@ -19,18 +20,21 @@
},
"scripts": {
"clean": "rm -rf dist",
"build": "tsc -p tsconfig.build.json",
"build": "tsc -p tsconfig.build.json && node scripts/post-build.js && cp dist/internal.d.ts dist/internal.d.cts",
"test": "vitest run",
"lint": "eslint --max-warnings=0 src"
},
"devDependencies": {
"@babel/plugin-transform-typescript": "^7.16.7",
"@rollup/plugin-babel": "^5.3.0",
"@types/caller": "^1.0.0",
"@types/dedent": "^0.7.0",
"@types/node": "^17.0.4",
"@types/ramda": "^0.27.62",
"@types/resolve": "^1.20.1",
"c8": "^7.10.0",
"eslint": "^8.6.0",
"rollup": "^2.62.0",
"typescript": "4.6.0-dev.20220105",
"vite": "^2.7.7",
"vitest": "^0.0.115"
Expand Down
36 changes: 36 additions & 0 deletions packages/core/scripts/post-build.js
@@ -0,0 +1,36 @@
import path from 'path';
import {fileURLToPath} from 'url';
import {rollup} from 'rollup';
import {babel} from '@rollup/plugin-babel';

(async () => {
const project = path.join(fileURLToPath(import.meta.url), '..', '..');
const config = {
input: path.join(project, 'src', 'internal.ts'),
external: id => {
if (id.startsWith('.')) {
return false;
}

return path.relative(path.join(project, 'src'), id).startsWith('..');
},
plugins: [
{
transform(code, id) {
if (id.endsWith('.ts')) {
return code.replace(/\.js';/g, '.ts\';');
}
},
},
babel({plugins: ['@babel/plugin-transform-typescript'], extensions: ['.ts'], babelHelpers: 'bundled'}),
],
};
const bundle = await rollup(config);

const outuput = {
file: path.join(project, 'dist', 'internal.cjs'),
format: 'cjs',
exports: 'named',
};
await bundle.write(outuput);
})();
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Expand Up @@ -18,7 +18,7 @@ import {deprecatedWarn} from './deprecate.js';
import {pFilter, pMap, pReduce} from './async.js';
import {resolveFrom, resolveSync, dirFromImportMeta, importUserModule} from './resolve.js';
import {GitStatusResult, gitStatus} from './git/index.js';
import {compact} from './lang';
import {compact} from './lang.js';

export {
CommandDefinition,
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/internal.ts
@@ -0,0 +1 @@
export {resolveSync} from './resolve.js';
1 change: 1 addition & 0 deletions packages/core/src/logger.ts
@@ -1,5 +1,6 @@
// @ts-expect-error
import * as kolorist from 'kolorist';
// @ts-expect-error
import dedentString from 'dedent';
import {isInDebugMode} from './flag.js';

Expand Down
7 changes: 3 additions & 4 deletions packages/core/src/project.ts
@@ -1,10 +1,12 @@
import path from 'path';
import {existsSync} from 'fs';
import fs from 'fs/promises';
import {packageDirectory} from 'pkg-dir';
import {findUp} from 'find-up';
import {globby} from 'globby';
import {PackageInfo} from './interface.js';

export const resolveCacheLocation = async (name: string): Promise<string> => {
const {packageDirectory} = await import('pkg-dir');
const root = await packageDirectory();

if (!root) {
Expand All @@ -21,7 +23,6 @@ export const readPackageConfig = async (cwd: string): Promise<PackageInfo> => {
};

export const findGitRoot = async (cwd?: string): Promise<string | undefined> => {
const {findUp} = await import('find-up');
const gitDirectory = await findUp('.git', {cwd, type: 'directory'});
return gitDirectory && path.dirname(gitDirectory);
};
Expand All @@ -36,7 +37,6 @@ export const isMonorepo = async (cwd: string): Promise<boolean> => {
};

export const resolveMonorepoPackageDirectories = async (cwd: string): Promise<string[]> => {
const {globby} = await import('globby');
const packageInfo = await readPackageConfig(cwd);
const packages = packageInfo.workspaces
? (Array.isArray(packageInfo.workspaces) ? packageInfo.workspaces : packageInfo.workspaces.packages)
Expand All @@ -46,7 +46,6 @@ export const resolveMonorepoPackageDirectories = async (cwd: string): Promise<st
};

export const findMonorepoRoot = async (cwd: string): Promise<string> => {
const {findUp} = await import('find-up');
const dir = await findUp('packages', {cwd, type: 'directory'});

if (!dir) {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/resolve.ts
Expand Up @@ -3,6 +3,7 @@ import fs from 'fs';
import {fileURLToPath} from 'url';
import {bundleRequire} from 'bundle-require';
import resolveCore from 'resolve';
// @ts-expect-error
import caller from 'caller';

export const resolveFrom = (base: string) => (id: string) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/doctor/src/migration/v2/entry.ts
@@ -1,4 +1,5 @@
import path from 'path';
import {globby} from 'globby';
import {pFilter} from '@reskript/core';
import {warn} from '../logger.js';

Expand All @@ -9,7 +10,6 @@ const isEntryBroken = async (file: string) => {
};

export default async (cwd: string) => {
const {globby} = await import('globby');
const entryFiles = await globby('src/entries/**/*.config.js', {cwd, absolute: true});
const brokenEntries = await pFilter(entryFiles, isEntryBroken);
if (brokenEntries.length) {
Expand Down
3 changes: 1 addition & 2 deletions packages/doctor/src/migration/v2/svg.ts
@@ -1,5 +1,6 @@
import path from 'path';
import fs from 'fs/promises';
import {globby} from 'globby';
import {pFilter} from '@reskript/core';
import {tip, warn} from '../logger.js';

Expand All @@ -9,7 +10,6 @@ const containsLegacySvgImport = async (file: string) => {
};

const checkScriptImport = async (cwd: string) => {
const {globby} = await import('globby');
const files = await globby('src/**/*.{js,jsx,tsx}', {cwd});
const warnings = await pFilter(files, containsLegacySvgImport);
if (warnings.length) {
Expand All @@ -26,7 +26,6 @@ const containsLegacySvgUrl = async (file: string) => {
};

const checkCssUrl = async (cwd: string) => {
const {globby} = await import('globby');
const files = await globby('src/**/*.{css,less}', {cwd});
const warnings = await pFilter(files, containsLegacySvgUrl);
if (warnings.length) {
Expand Down
2 changes: 1 addition & 1 deletion packages/init/src/check.ts
@@ -1,4 +1,5 @@
import path from 'path';
import {globby} from 'globby';
import {logger} from '@reskript/core';

const ALLOWED_EXISTING_FILES = new Set([
Expand All @@ -14,7 +15,6 @@ const ALLOWED_EXISTING_FILES = new Set([
]);

const checkDirectoryHasTooManyFiles = async (cwd: string) => {
const {globby} = await import('globby');
const files = await globby(`${cwd}/**`, {dot: true, onlyFiles: false, deep: 1});

if (files.length > ALLOWED_EXISTING_FILES.size) {
Expand Down
3 changes: 1 addition & 2 deletions packages/init/src/run/copy.ts
@@ -1,14 +1,13 @@
import path from 'path';
import {existsSync} from 'fs';
import fs from 'fs/promises';
import {globby} from 'globby';
import ora from 'ora';
import {dirFromImportMeta} from '@reskript/core';
import {UserOptions} from '../interface.js';


export default async (cwd: string, options: UserOptions) => {
const {globby} = await import('globby');

const spinner = ora('Copying initial files');
spinner.start();

Expand Down

0 comments on commit 1f1fcfb

Please sign in to comment.