Skip to content

Commit

Permalink
Merge branch 'main' into fix/when-no-partials-get-more-chart
Browse files Browse the repository at this point in the history
  • Loading branch information
clChenLiang authored Aug 27, 2023
2 parents c08503e + bc1f8da commit 09b4b7c
Show file tree
Hide file tree
Showing 48 changed files with 557 additions and 5,283 deletions.
7 changes: 7 additions & 0 deletions .changeset/lazy-hotels-compete.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@modern-js/builder': patch
---

feat(builder): add tailwind config to webpack build dependencies

feat(builder): 添加 tailwind config 到 webpack build dependencies 中
12 changes: 12 additions & 0 deletions .changeset/shy-countries-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@modern-js/builder-shared': patch
'@modern-js/plugin-tailwindcss': patch
'@modern-js/module-tools-docs': patch
'@modern-js/main-doc': patch
'@modern-js/utils': patch
'@modern-js/doc-core': patch
---

feat(builder): support custom logger in dev server

feat(builder): 支持自定义 logger
9 changes: 7 additions & 2 deletions packages/builder/builder-shared/src/devServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
} from './types';
import type { ModernDevServerOptions, Server } from '@modern-js/server';
import { merge } from '@modern-js/utils/lodash';
import { logger, debug } from './logger';
import { logger as defaultLogger, debug } from './logger';
import { DEFAULT_PORT } from './constants';
import { createAsyncHook } from './createHook';
import { getServerOptions, printServerURLs } from './prodServer';
Expand Down Expand Up @@ -95,10 +95,14 @@ export async function startDevServer<
printURLs = true,
strictPort = false,
serverOptions = {},
logger: customLogger,
getPortSilently,
}: StartDevServerOptions & {
defaultPort?: number;
} = {},
) {
const logger = customLogger ?? defaultLogger;

logger.info('Starting dev server...');

if (!process.env.NODE_ENV) {
Expand All @@ -112,6 +116,7 @@ export async function startDevServer<

const port = await getPort(builderConfig.dev?.port || DEFAULT_PORT, {
strictPort,
slient: getPortSilently,
});

const host =
Expand Down Expand Up @@ -165,7 +170,7 @@ export async function startDevServer<
}
}

await printServerURLs(urls, 'Dev server');
await printServerURLs(urls, 'Dev server', logger);
}

await options.context.hooks.onAfterStartDevServerHook.call({ port });
Expand Down
8 changes: 6 additions & 2 deletions packages/builder/builder-shared/src/prodServer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import prodServer, { type ModernServerOptions } from '@modern-js/prod-server';
import { logger } from './logger';
import prodServer, {
Logger,
type ModernServerOptions,
} from '@modern-js/prod-server';
import { logger as defaultLogger } from './logger';
import { DEFAULT_PORT } from './constants';
import type {
BuilderContext,
Expand Down Expand Up @@ -32,6 +35,7 @@ export const getServerOptions = (
export async function printServerURLs(
urls: Array<{ url: string; label: string }>,
name = 'Server',
logger: Logger = defaultLogger,
) {
const { chalk } = await import('@modern-js/utils');
let message = `${name} running at:\n\n`;
Expand Down
3 changes: 3 additions & 0 deletions packages/builder/builder-shared/src/types/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { Compiler, MultiCompiler } from 'webpack';
import type { BuilderMode, CreateBuilderOptions } from './builder';
import type { Server, ModernDevServerOptions } from '@modern-js/server';
import type { AddressUrl } from '@modern-js/utils';
import { Logger } from '@modern-js/prod-server';

export type Bundler = 'webpack' | 'rspack';

Expand All @@ -12,7 +13,9 @@ export type CreateCompilerOptions = { watch?: boolean };
export type StartDevServerOptions = {
compiler?: Compiler | MultiCompiler;
printURLs?: boolean | ((urls: AddressUrl[]) => AddressUrl[]);
logger?: Logger;
strictPort?: boolean;
getPortSilently?: boolean;
serverOptions?: Partial<Omit<ModernDevServerOptions, 'config'>> & {
config?: Partial<ModernDevServerOptions['config']>;
};
Expand Down
59 changes: 39 additions & 20 deletions packages/builder/builder/src/plugins/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,44 @@ function getCacheDirectory(
return join(context.cachePath, context.bundlerType);
}

/**
* webpack can't detect the changes of framework config, tsconfig, tailwind config and browserslist config.
* but they will affect the compilation result, so they need to be added to buildDependencies.
*/
async function getBuildDependencies(context: Readonly<BuilderContext>) {
const { findExists } = await import('@modern-js/utils');
const rootPackageJson = join(context.rootPath, 'package.json');
const browserslistConfig = join(context.rootPath, '.browserslistrc');

const buildDependencies: Record<string, string[]> = {
packageJson: [rootPackageJson],
};

if (context.configPath) {
buildDependencies.config = [context.configPath];
}

if (context.tsconfigPath) {
buildDependencies.tsconfig = [context.tsconfigPath];
}

if (await isFileExists(browserslistConfig)) {
buildDependencies.browserslistrc = [browserslistConfig];
}

const tailwindExts = ['ts', 'js', 'cjs', 'mjs'];
const configs = tailwindExts.map(ext =>
join(context.rootPath, `tailwind.config.${ext}`),
);
const tailwindConfig = findExists(configs);

if (tailwindConfig) {
buildDependencies.tailwindcss = [tailwindConfig];
}

return buildDependencies;
}

export const builderPluginCache = (): DefaultBuilderPlugin => ({
name: 'builder-plugin-cache',

Expand All @@ -59,27 +97,8 @@ export const builderPluginCache = (): DefaultBuilderPlugin => ({

const { context } = api;
const cacheConfig = typeof buildCache === 'boolean' ? {} : buildCache;

const cacheDirectory = getCacheDirectory(cacheConfig, context);
const rootPackageJson = join(context.rootPath, 'package.json');
const browserslistConfig = join(context.rootPath, '.browserslistrc');

/**
* webpack can't detect the changes of framework config, tsconfig and browserslist config.
* but they will affect the compilation result, so they need to be added to buildDependencies.
*/
const buildDependencies: Record<string, string[]> = {
packageJson: [rootPackageJson],
};
if (context.configPath) {
buildDependencies.config = [context.configPath];
}
if (context.tsconfigPath) {
buildDependencies.tsconfig = [context.tsconfigPath];
}
if (await isFileExists(browserslistConfig)) {
buildDependencies.browserslistrc = [browserslistConfig];
}
const buildDependencies = await getBuildDependencies(context);

await validateCache(cacheDirectory, buildDependencies);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ exports[`plugins/cache > 'should add cache config correctly' 1`] = `
"packageJson": [
"<ROOT>/tests/plugins/package.json",
],
"tailwindcss": [
"/root/tailwind.config.ts",
],
},
"cacheDirectory": "<ROOT>/tests/plugins/node_modules/.cache/webpack",
"name": "web-development",
Expand All @@ -22,6 +25,9 @@ exports[`plugins/cache > 'should custom cache directory by user' 1`] = `
"packageJson": [
"<ROOT>/tests/plugins/package.json",
],
"tailwindcss": [
"/root/tailwind.config.ts",
],
},
"cacheDirectory": "<ROOT>/tests/plugins/node_modules/.cache/tmp",
"name": "web-development",
Expand All @@ -46,6 +52,9 @@ exports[`plugins/cache > 'should watch framework config change' 1`] = `
"packageJson": [
"<ROOT>/tests/plugins/package.json",
],
"tailwindcss": [
"/root/tailwind.config.ts",
],
},
"cacheDirectory": "<ROOT>/tests/plugins/node_modules/.cache/webpack",
"name": "web-development",
Expand All @@ -61,6 +70,9 @@ exports[`plugins/cache > 'should watch tsconfig change' 1`] = `
"packageJson": [
"<ROOT>/tests/plugins/package.json",
],
"tailwindcss": [
"/root/tailwind.config.ts",
],
"tsconfig": [
"/path/to/tsconfig.json",
],
Expand Down
15 changes: 14 additions & 1 deletion packages/builder/builder/tests/plugins/cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
import { join } from 'path';
import { expect, describe, it } from 'vitest';
import { vi, expect, describe, it } from 'vitest';
import * as shared from '@modern-js/builder-shared';
import { builderPluginCache } from '@/plugins/cache';

vi.mock('@modern-js/utils', async importOriginal => {
const mod = await importOriginal<any>();
return {
...mod,
findExists: (files: string[]) => {
if (files.some(file => file.includes('tailwind'))) {
return '/root/tailwind.config.ts';
}
return mod.findExists(files);
},
};
});

describe('plugins/cache', () => {
const cases = [
{
Expand Down
51 changes: 50 additions & 1 deletion packages/document/builder-doc/docs/en/api/builder-instance.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,10 @@ type StartDevServerOptions = {
compiler?: Compiler | MultiCompiler;
// passing through the build-independent dev server configuration
serverOptions?: Partial<ModernDevServerOptions>;
// Whether to get the port silently, the default is false
getPortSliently?: boolean;
// custom logger
logger?: Logger;
};

type StartServerResult = {
Expand Down Expand Up @@ -293,6 +297,52 @@ await builder.startDevServer({
});
```

### Get Port Silently

In some cases, the default startup port number is already occupied. In this situation, Builder will automatically increment the port number until it finds an available one. This process will output a prompt log. If you do not want this log, you can set `getPortSliently` to `true`.

```ts
await builder.startDevServer({
getPortSliently: true,
});
```

### Custom Logger

By default, Builder uses `@modern-js/utils/logger` to output logs. You can customize the log output object through the `logger` parameter.

```ts
const customLogger = {
// You need to define the following methods
info(msg: string) {
console.log(msg);
},
error(msg: string) {
console.error(msg);
},
warn(msg: string) {
console.warn(msg);
},
success(msg: string) {
console.log(`✅ msg`);
},
debug(msg: string) {
if (process.env.DEBUG) {
console.log(msg);
}
},
log(msg: string) {
console.log(msg);
};
}

await builder.startDevServer({
logger: customLogger,
});
```

Then Builder will use the custom logger to output logs.

## builder.serve

Start a server to preview the production build locally. This method should be executed after `builder.build`.
Expand Down Expand Up @@ -332,7 +382,6 @@ console.log(port); // 8080
await server.close();
```


## builder.createCompiler

Create a Compiler object.
Expand Down
52 changes: 50 additions & 2 deletions packages/document/builder-doc/docs/zh/api/builder-instance.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,10 @@ type StartDevServerOptions = {
compiler?: Compiler | MultiCompiler;
// 透传与构建无关的 dev server 配置
serverOptions?: Partial<ModernDevServerOptions>;
// 是否在启动时静默获取端口号,默认为 false
getPortSliently?: boolean;
// 自定义日志输出对象
logger?: Logger;
};

type StartServerResult = {
Expand Down Expand Up @@ -293,6 +297,52 @@ await builder.startDevServer({
});
```

### 静默获取端口号

某些情况下,默认启动的端口号已经被占用,此时 Builder 会自动递增端口号,直至找到一个可用端口。这个过程会输出提示日志,如果你不希望这段日志,可以将 `getPortSliently` 设置为 `true`

```ts
await builder.startDevServer({
getPortSliently: true,
});
```

### 自定义日志输出对象

默认情况下,Builder 会使用 `@modern-js/utils/logger` 来输出日志,你可以通过 `logger` 参数来自定义日志输出对象。

```ts
const customLogger = {
// 你需要定义以下的方法
info(msg: string) {
console.log(msg);
},
error(msg: string) {
console.error(msg);
},
warn(msg: string) {
console.warn(msg);
},
success(msg: string) {
console.log(`✅ msg`);
},
debug(msg: string) {
if (process.env.DEBUG) {
console.log(msg);
}
},
log(msg: string) {
console.log(msg);
};
}

await builder.startDevServer({
logger: customLogger,
});
```

这样,Builder 会使用你自定义的日志输出对象来输出日志。

## builder.serve

在本地启动 Server 来预览生产环境构建的产物,需要在 `builder.build` 方法之后执行。
Expand All @@ -317,7 +367,6 @@ function server(): Promise<StartServerResult>;
await builder.serve();
```


`serve` 会返回以下参数:

- `urls`:访问 Server 的 URLs
Expand All @@ -333,7 +382,6 @@ console.log(port); // 8080
await server.close();
```


## builder.createCompiler

创建一个 compiler 对象。
Expand Down
Loading

0 comments on commit 09b4b7c

Please sign in to comment.