Skip to content

Commit

Permalink
feat: enhanced .kktrc.{cjs,mjs,ts,js} config.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaywcjlove committed Jun 2, 2023
1 parent 97997ad commit 9ef2499
Show file tree
Hide file tree
Showing 11 changed files with 52 additions and 80 deletions.
17 changes: 16 additions & 1 deletion core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,22 @@ $ npm run build

## Configuration File

Supports `.kktrc.js` and `.kktrc.ts`.
Supports `.kktrc.js` and `.kktrc.ts`. `@7.4+` above supports `.cjs`, `.mjs`, `.ts`, `.js`.

```ts
.kktrc.js
.kktrc.ts
.kktrc.cjs
.kktrc.mjs
.config/kktrc.js
.config/kktrc.ts
.config/kktrc.cjs
.config/kktrc.mjs
kkt.config.js
kkt.config.ts
kkt.config.cjs
kkt.config.mjs
```

```typescript
import express from 'express';
Expand Down
3 changes: 1 addition & 2 deletions core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
"react-scripts": ">=2.1.3"
},
"dependencies": {
"@babel/register": "~7.17.7",
"@kkt/resolve-fallback": "^7.4.17",
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^13.0.0",
Expand All @@ -51,6 +50,7 @@
"@types/react-dev-utils": "~9.0.10",
"@types/semver": "~7.5.0",
"@types/testing-library__jest-dom": "^5.14.3",
"auto-config-loader": "^1.4.0",
"ajv": "^8.8.0",
"eslint-config-react-app": "^7.0.0",
"fs-extra": "~10.1.0",
Expand All @@ -65,7 +65,6 @@
"resolve-package-path": "~4.0.3",
"sass": "^1.45.1",
"semver": "~7.5.0",
"ts-node": "^10.9.1",
"typescript": "^5.0.4",
"webpack": "^5.65.0"
}
Expand Down
1 change: 1 addition & 0 deletions core/src/bin/kkt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const helpStr = `
--help, -h Displays help information.
--app-src Specify the entry directory.
--docs Static asset preview in package(Dev mode works).
--config-overrides Specify the directory where the configuration is located.
--no-open-browser Do not open in browser.
--no-clear-console Do not clear the command line information.
Expand Down
4 changes: 2 additions & 2 deletions core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { ParsedArgs } from 'minimist';
import { WebpackConfiguration, LoaderConfOptions, DevServerOptions } from './utils/loaderConf';
import { WebpackConfiguration, LoaderConfOptions, DevServerOptions } from './utils/conf';
import { getDocsData } from './plugins/staticDoc';

export * from 'mocker-api';
export * from './overrides/paths';
export * from './utils/loaderConf';
export * from './utils/conf';
export * from './utils/getStyleLoaders';
export * from './plugins/miniCssExtractPlugin';
export * from './utils/path';
Expand Down
2 changes: 1 addition & 1 deletion core/src/overrides/printInstructions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import chalk from 'chalk';
import { reactDevUtils } from '../utils/path';
import { getDocsData } from '../plugins/staticDoc';
import { DevServerOptions } from '../utils/loaderConf';
import { DevServerOptions } from '../utils/conf';
import { StartArgs } from '..';

export type OverridesPrintInstructionsOption = StartArgs & DevServerOptions & {};
Expand Down
2 changes: 1 addition & 1 deletion core/src/plugins/staticDoc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import express from 'express';
import path from 'path';
import WebpackDevServer from 'webpack-dev-server';
import resolvePackagePath from 'resolve-package-path';
import { DevServerOptions, WebpackConfiguration } from '../utils/loaderConf';
import { DevServerOptions, WebpackConfiguration } from '../utils/conf';
import { StartArgs } from '..';

export interface DocsDataResult {
Expand Down
13 changes: 10 additions & 3 deletions core/src/scripts/build.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
process.env.NODE_ENV = 'production';

import path from 'path';
import { Configuration } from 'webpack';
import resolveFallback from '@kkt/resolve-fallback';
import { KKTRC, WebpackConfiguration, loaderConf } from '../utils/loaderConf';
import { reactScripts, isWebpackFactory, getConfPath } from '../utils/path';
import { loaderConfig, WebpackConfiguration } from '../utils/conf';
import { reactScripts, isWebpackFactory } from '../utils/path';
import { overridePaths } from '../overrides/paths';
import { miniCssExtractPlugin } from '../plugins/miniCssExtractPlugin';
import { checkRequiredFiles } from '../overrides/checkRequired';
Expand All @@ -17,7 +18,13 @@ export default async function build(argvs: BuildArgs) {
await checkRequiredFiles(paths, isNotCheckHTML);
const webpackConfigPath = `${reactScripts}/config/webpack.config${!isWebpackFactory ? '.prod' : ''}`;
const createWebpackConfig: (env: string) => Configuration = require(webpackConfigPath);
const kktrc: KKTRC = await loaderConf(getConfPath(argvs.configName));
const configOverrides = argvs['config-overrides'];
const kktrc = await loaderConfig(argvs.configName || '.kktrc', {
/**
* Specify the directory where the configuration is located.
*/
cwd: configOverrides ? path.resolve(process.cwd(), argvs['config-overrides']) : undefined,
});
const overridesHandle = kktrc.default || argvs.overridesWebpack;

if (overridesHandle && typeof overridesHandle === 'function') {
Expand Down
13 changes: 10 additions & 3 deletions core/src/scripts/start.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
process.env.NODE_ENV = 'development';

import fs from 'fs';
import path from 'path';
import webpack, { Configuration } from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import evalSourceMapMiddleware from 'react-dev-utils/evalSourceMapMiddleware';
import redirectServedPath from 'react-dev-utils/redirectServedPathMiddleware';
import clearConsole from 'react-dev-utils/clearConsole';
import resolveFallback from '@kkt/resolve-fallback';
import noopServiceWorkerMiddleware from 'react-dev-utils/noopServiceWorkerMiddleware';
import { KKTRC, DevServerConfigFunction, WebpackConfiguration, loaderConf } from '../utils/loaderConf';
import { reactScripts, isWebpackFactory, proxySetup, getConfPath } from '../utils/path';
import { loaderConfig, WebpackConfiguration, DevServerConfigFunction } from '../utils/conf';
import { reactScripts, isWebpackFactory, proxySetup } from '../utils/path';
import { overridePaths } from '../overrides/paths';
import { overridesOpenBrowser } from '../overrides/openBrowser';
import { overridesClearConsole } from '../overrides/clearConsole';
Expand All @@ -34,7 +35,13 @@ export default async function start(argvs: StartArgs) {
const createWebpackConfig: (env: string) => Configuration = require(webpackConfigPath);
const createDevServerConfig: DevServerConfigFunction = require(devServerConfigPath);
require('react-scripts/config/env');
const kktrc: KKTRC = await loaderConf(getConfPath(argvs.configName));
const configOverrides = argvs['config-overrides'];
const kktrc = await loaderConfig(argvs.configName || '.kktrc', {
/**
* Specify the directory where the configuration is located.
*/
cwd: configOverrides ? path.resolve(process.cwd(), argvs['config-overrides']) : undefined,
});
await overridesClearConsole(argvs);
await overridesOpenBrowser(argvs);

Expand Down
2 changes: 1 addition & 1 deletion core/src/utils/cacheData.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { KKTRC } from './loaderConf';
import { KKTRC } from './conf';

type CacheData = {
proxySetup?: KKTRC['proxySetup'];
Expand Down
44 changes: 8 additions & 36 deletions core/src/utils/loaderConf.ts → core/src/utils/conf.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,11 @@
import load, { AutoConfOption } from 'auto-config-loader';
import { Configuration } from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import type WebpackDevServer from 'webpack-dev-server';
import { MockerOption, MockerProxyRoute } from 'mocker-api';
import express from 'express';
import fs from 'fs-extra';
import { ParsedArgs } from 'minimist';
import type express from 'express';
import { OverridePaths } from '../overrides/paths';

const tsOptions = {
compilerOptions: {
sourceMap: false,
target: 'es6',
module: 'commonjs',
moduleResolution: 'node',
allowJs: false,
declaration: true,
strict: true,
noUnusedLocals: true,
experimentalDecorators: true,
resolveJsonModule: true,
esModuleInterop: true,
removeComments: false,
},
};

export type MockerAPIOptions = {
path: string | string[] | MockerProxyRoute;
option?: MockerOption;
Expand Down Expand Up @@ -77,23 +60,12 @@ export type KKTRC = {
) => WebpackConfiguration | Promise<WebpackConfiguration>;
};

export async function loaderConf(rcPath: string): Promise<KKTRC> {
let kktrc: KKTRC = {};
const confJsPath = `${rcPath}.js`;
const confTsPath = `${rcPath}.ts`;
export async function loaderConfig(namespace: string = 'kkt', option?: AutoConfOption<KKTRC>) {
/** Old ~~`.kktrc`~~ => New `kkt` */
const name = namespace.replace(/^\.(.*)rc$/g, '$1');
try {
if (fs.existsSync(confTsPath)) {
require('ts-node').register(tsOptions);
kktrc = await import(confTsPath);
return kktrc;
}
if (fs.existsSync(confJsPath)) {
require('@babel/register')({
presets: [[require.resolve('babel-preset-react-app'), { runtime: 'classic', useESModules: false }]],
});
kktrc = await import(confJsPath);
}
return kktrc;
const data = load<KKTRC>(name, option);
return (data || {}) as KKTRC;
} catch (error) {
const message = error && error instanceof Error && error.message ? error.message : '';
console.log('Invalid \x1b[31;1m .kktrc.js \x1b[0m file.\n', error);
Expand Down
31 changes: 1 addition & 30 deletions core/src/utils/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,6 @@ const argvs = minimist(args);

/** App Path */
const projectDir = path.resolve(fs.realpathSync(process.cwd()));
const customOpts = require(path.resolve(projectDir, 'package.json'))['kkt'] || {};

function getConfPath(confName = '.kktrc') {
/**
* 默认从 package.json 指定配置文件目录和当前目录根目录 `.kktrc` 配置文件
* `<Project Root Path>/.kktrc`
*
* ```js
* {
* "kkt": {
* "path": "./config/.kktrc"
* }
* }
* ```
*/
let confPath = customOpts.path ? `${projectDir}/${customOpts.path}` : `${projectDir}/${confName}`;

if (argvs['config-overrides']) {
confPath = path.resolve(argvs['config-overrides']);
}
confPath = confPath.replace(/\.(js|ts)$/gi, '');
return path.resolve(confPath);
}

/**
* Package [`react-scripts`](http://npmjs.com/react-scripts) directory location
Expand Down Expand Up @@ -87,10 +64,4 @@ const scriptPkg = require(`${reactScripts}/package.json`);
*/
const isWebpackFactory = semver.gte(scriptPkg && scriptPkg.version, '2.1.2');

/**
* Compatible API
* @deprecated
*/
const configOverrides = getConfPath();

export { proxySetup, projectDir, reactScripts, reactDevUtils, configOverrides, getConfPath, isWebpackFactory, paths };
export { proxySetup, projectDir, reactScripts, reactDevUtils, isWebpackFactory, paths };

1 comment on commit 9ef2499

@jaywcjlove
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.