---
sidebar_position: 1
---

# buildConfig

`buildConfig` is a configuration option that describes how to compile and generate build artifacts. It contains all the configurations related to the build process.

- **Type**: `object | object[]`

:::tip
Before start using `buildConfig`, please read the following documentation to understand its purpose:

- [Modifying Output Artifacts](/guide/basic/modify-output-product.html)
- [In-Depth Understanding of the Build Process](/guide/advance/in-depth-about-build.html)

:::

## alias

- **Type**: `Record<string, string> | Function`
- **Default**: `{'@': 'src',}`

:::tip
For TypeScript projects, you only need to configure [compilerOptions.paths](https://www.typescriptlang.org/tsconfig#paths) in `tsconfig.json`, Modern.js Module will automatically recognize the alias in `tsconfig.json`, so there is no need to configure the `alias` field additionally.
:::

```js title="modern.config.ts"
export default {
  buildConfig: {
    alias: {
      '@common': '. /src/common',
    },
  },
};
```

After the above configuration is done, if `@common/Foo.tsx` is referenced in the code, it will map to the `<project>/src/common/Foo.tsx` path.

When the value of `alias` is defined as a function, you can accept the pre-defined alias object and modify it.

```js title="modern.config.ts"
export default {
  buildConfig: {
    alias: alias => {
      alias['@common'] = '. /src/common';
    },
  },
};
```

It is also possible to return a new object as the final result in the function, which will override the pre-defined alias object.

```js title="modern.config.ts"
export default {
  buildConfig: {
    alias: alias => {
      return {
        '@common': '. /src/common',
      };
    },
  },
};
```

## asset

Contains configuration related to static assets.

## asset.name

Static resource output file name.

- **Type**: `string | ((assetPath) => name)`
- **Default**: `[name].[hash].[ext]`

When asset.name is a string, it will automatically replace [name], [ext], and [hash], respectively replaced by the file name, extension, and file hash.

Also you can use asset.name as a function, and the return is output asset name. At this time, this function receives a parameter assetPath, which corresponds to the resource path.

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    asset: {
      // no hash
      name: [name].[ext],
      // any logic
      // name: (assetPath) => 'any.png',
    },
  },
});
```

## asset.limit

Used to set the threshold for static assets to be automatically inlined as base64.

By default, Modern.js Module will inline assets such as images, fonts and media smaller than 10KB during bundling. They are Base64 encoded and inlined in the bundles, eliminating the need for separate HTTP requests.

You can adjust this threshold by modifying the `limit` config.

- **Type**: `number`
- **Default**: `10 * 1024`

For example, set `limit` to `0` to avoid assets inlining:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    asset: {
      limit: 0,
    },
  },
});
```

## asset.path

Static resource output path, will be based on [outDir](/api/config/build-config#outdir)

- **Type**: `string`
- **Default**: `assets`

## asset.publicPath

The CDN prefix given to unlinked assets when bundling.

- **Type**: `string`
- **Default**: `undefined`

```js title="modern.config.ts"
export default {
  buildConfig: {
    asset: {
      publicPath: 'https://xxx/',
    },
  },
};
```

At this point, all static assets will be prefixed with `https://xxx/`.

## asset.svgr

Packaged to handle svg as a React component, options reference [svgr](https://react-svgr.com/docs/options/), plus support for two configuration options `include` and `exclude` to match the svg file to be handled

- **Type**: `boolean | object`
- **Default**: `false`

When svgr feature is enabled, you can use svg as a component using the default export.

```js title="index.ts"
// true
import Logo from './logo.svg';

export default () => <Logo />;
```

:::

When enabled, the type of svg used can be modified by initing a new declaration file and adding to the `modern-app-env.d.ts`:

```ts title="your-app-env.d.ts"
declare module '*.svg' {
  const src: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
  export default src;
}
```

```ts title="modern-app-env.d.ts"
/// <reference path='./your-app-env.d.ts' />
/// <reference types='@modern-js/module-tools/types' />
```

## asset.svgr.include

Set the matching svg file

- **Type**: `string | RegExp | (string | RegExp)[]`
- **Default**: `/\.svg$/`

## asset.svgr.exclude

Set unmatched svg files

- **Type**: `string | RegExp | (string | RegExp)[]`
- **Default**: `undefined`

## asset.svgr.exportType

Used to configure the SVG export type when using SVGR.

- **Type**: `'named' | 'default'`
- **Default**: `default`

when it is 'named', use the following syntax:

```js title="index.ts"
import { ReactComponent } from './logo.svg';
```

The named export defaults to `ReactComponent`, and can be customized with the `asset.svgr.namedExport`.

## autoExtension

Suffixes for js files and type description files in automation based on [format](#format) and [type](https://nodejs.org/api/packages.html#type).

- **Type**: `boolean`
- **Default**: `false`
- **Version**: `>=MAJOR_VERSION.38.0`

When disabled, js artifacts are suffixed with `.js` and type description files are suffixed with `d.ts`.

When enabled, node loads `.js` as esm by default when type is `module`, so when we want to output cjs artifacts, the js product is suffixed with `.cjs` and the type description file is suffixed with `d.cts`.

On the other hand, if the type field is missing or the type is `commonjs`, node loads the `.js` file as cjs by default.
So when we want to output esm output, the js output is suffixed with `.mjs` and the type description file is suffixed with `d.mts`.

:::warning
When used in bundleless mode, we have an extra step of processing the import/export statement in each file. We will suffix the relative path to the js file, possibly `.mjs` or `.cjs`, depending on your package configuration.
You can disable this step by [redirect.autoExtension](#redirect).

Notice [noUselessIndex](https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-useless-path-segments.md#nouselessindex) will break this behavior, you should disable it.
If you need to use this configuration in bundleless, please patch the `index`, e.g. if utils is a folder, you need to rewrite `import * from './utils'` to `import * from './utils/index'`
:::

```ts title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    autoExtension: true,
  },
});
```

## autoExternal

Automatically externalize project dependencies and peerDependencies and not package them into the final bundle

- **Type**: `boolean | object`
- **Default**: `true`

When we want to turn off the default handling behavior for third-party dependencies, we can do so by:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    autoExternal: false,
  },
});
```

This way the dependencies under `"dependencies"` and `"peerDependencies"` will be bundled. If you want to turn off the processing of only one of these dependencies, you can use the
`buildConfig.autoExternal` in the form of an object.

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    autoExternal: {
      dependencies: false,
      peerDependencies: false,
    },
  },
});
```

## autoExternal.dependencies

Whether or not the dep dependencies of the external project are needed

- **Type**: `boolean`
- **Default**: `true`

## autoExternal.peerDependencies

Whether to require peerDep dependencies for external projects

- **Type**: `boolean`
- **Default**: `true`

## banner

Provides the ability to inject content into the top and bottom of each JS , CSS and DTS file.

```ts
interface BannerAndFooter {
  js?: string;
  css?: string;
  dts?: string;
}
```

- **Type**: `BannerAndFooter`
- **Default**: `{}`
- **Version**: `>=MAJOR_VERSION.36.0`

Let's say you want to add copyright information to JS and CSS files.

```ts
import { moduleTools, defineConfig } from '@modern-js/module-tools';

const copyRight = `/*
 © Copyright 2020 example.com or one of its affiliates.
 * Some Sample Copyright Text Line
 * Some Sample Copyright Text Line
*/`;

export default defineConfig({
  plugins: [moduleTools()],
  buildConfig: {
    banner: {
      js: copyRight,
      css: copyRight,
    },
  },
});
```

## buildType

The build type, `bundle` will package your code, `bundleless` will only do the code conversion

- **Type**: `'bundle' | 'bundleless'`
- **Default**: `'bundle'`

## copy

Copies the specified file or directory into the build output directory

- **Type**: `object[]`
- **Default**: `[]`

```js
export default {
  buildConfig: {
    copy: [{ from: '. /src/assets', to: '' }],
  },
};
```

Reference for array settings: [copy-webpack-plugin patterns](https://github.com/webpack-contrib/copy-webpack-plugin#patterns)

:::tip
Refer to [Use the Copy Tools](/guide/advance/copy) for the complete usage of the `copy` option.
:::

## copy.patterns

- **Type**: `CopyPattern[]`
- **Default**: `[]`

```ts
interface CopyPattern {
  from: string;
  to?: string;
  context?: string;
  globOptions?: globby.GlobbyOptions;
}
```

## copy.options

- **Type**:

```ts
type Options = {
  concurrency?: number;
  enableCopySync?: boolean;
};
```

- **Default**: `{ concurrency: 100, enableCopySync: false }`

- `concurrency`: Specifies how many copy tasks to execute in parallel.
- `enableCopySync`: Uses [`fs.copySync`](https://github.com/jprichardson/node-fs-extra/blob/master/lib/copy/copy-sync.js) by default, instead of [`fs.copy`](https://github.com/jprichardson/node-fs-extra/blob/master/lib/copy/copy.js).

## define

Define global variables that will be injected into the code

- **Type**: `Record<string, string>`
- **Default**: `{}`

Since the `define` function is implemented by global text replacement, you need to ensure that the global variable values are strings. A safer approach is to convert the value of each global variable to a string, as follows.

:::info
Modern.js automatically performs JSON serialization handling internally, so manual serialization is not required.

If automatic serialization is not needed, you can define [`alias`](https://esbuild.github.io/api/#alias) using [`esbuildOptions`](/api/config/build-config.html#esbuildoptions) configuration.

:::

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    define: {
      VERSION: require('./package.json').version || '0.0.0',
    },
  },
});
```

If the project is a TypeScript project, then you may need to add the following to the `.d.ts` file in the project source directory.

> If the `.d.ts` file does not exist, then you can create it manually.

```ts title="env.d.ts"
declare const YOUR_ADD_GLOBAL_VAR;
```

You can also replace environment variable:

```js
import { defineConfig } from '@modern-js/module-tools';
export default defineConfig({
  buildConfig: {
    define: {
      'process.env.VERSION': process.env.VERSION || '0.0.0',
    },
  },
});
```

With the above configuration, we can put the following code.

```js
// pre-compiler code
console.log(process.env.VERSION);
```

When executing `VERSION=1.0.0 modern build`, the conversion is:

```js
// compiled code
console.log('1.0.0');
```

:::tip
To prevent excessive global replacement substitution, it is recommended that the following two principles be followed when using

- Use upper case for global constants
- Customize the prefix and suffix of global constants to ensure uniqueness

:::

## dts

The dts file generates the relevant configuration, by default it generates.

- **Type**: `false | object`
- **Default**:

```js
{
  abortOnError: true,
  distPath: './',
  only: false,
}
```

## dts.abortOnError

Whether to allow the build to succeed if a type error occurs.

- **Type**: `boolean`
- **Default**: `true`

**By default, type errors will cause the build to fail**. When `abortOnError` is set to `false`, the build will still succeed even if there are type issues in the code:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    dts: {
      abortOnError: false,
    },
  },
});
```

:::warning
When this configuration is disabled, there is no guarantee that the type files will be generated correctly. In `buildType: 'bundle'`, which is the bundle mode, type files will not be generated.
:::

## dts.distPath

The output path of the dts file, based on [outDir](/api/config/build-config#outdir)

- **Type**: `string`
- **Default**: `./`

For example, output to the `types` directory under the `outDir`:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    dts: {
      distPath: './types',
    },
  },
});
```

## dts.enableTscBuild

Enable the tsc '--build' option. When using project reference,
you can use the '--build' option to achieve cooperation between projects and speed up the build speed.

This option requires version > MAJOR_VERSION.43.0,In fact,
we experimentally enabled this option in the MAJOR_VERSION.42.0 version, but the many problems it brought forced us to enable it dynamically.

```warning
When this option is enabled, to meet the build requirements, you must explicitly set 'declarationDir' or 'outDir' in tsconfig.json,
If you are not using TS >= 5.0 version, you also need to explicitly set 'declaration' and 'emitDeclarationOnly'.
```

- **Type**: `boolean`
- **Default**: `false`
- **Version**: `>MAJOR_VERSION.43.0`

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    dts: {
      enableTscBuild: true,
    },
  },
});
```

## dts.only

Whether to generate only type files during the build process without generating JavaScript output files.

- **Type**: `boolean`
- **Default**: `false`

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    dts: {
      only: true,
    },
  },
});
```

## dts.tsconfigPath

**deprecated**,use [tsconfig](#tsconfig) instead.

Specifies the path to the tsconfig file used to generate the type file.

```ts title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    dts: {
      tsconfigPath: './other-tsconfig.json',
    },
  },
});
```

## dts.respectExternal

When set to `false`, the type of third-party packages will be excluded from the bundle, when set to `true`, it will determine whether third-party types need to be bundled based on [externals](#externals).

When bundle d.ts, export is not analyzed, so any third-party package type you use may break your build, which is obviously uncontrollable.
So we can avoid it with this configuration.

- **Type**: `boolean`
- **Default**: `true`

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    dts: {
      respectExternal: false,
    },
  },
});
```

## esbuildOptions

Used to modify the [esbuild configuration](https://esbuild.github.io/api/).

- **Type**: `Function`
- **Build Type**: `Only supported for buildType: 'bundle'`
- **Default**: `c => c`

For example, if we need to modify the file extension of the generated files:

```ts title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    esbuildOptions: options => {
      options.outExtension = { '.js': '.mjs' };
      return options;
    },
  },
});
```

For example, register an esbuild plugin:

import RegisterEsbuildPlugin from '@site-docs-en/components/register-esbuild-plugin';

<RegisterEsbuildPlugin />

:::tip
We have done many extensions based on the original esbuild build. Therefore, when using this configuration, pay attention to the following:

1. Prefer to use the configuration that Modern.js Module provides. For example, esbuild does not support `target: 'es5'`, but we support this scenario internally using SWC. Setting `target: 'es5'` through esbuildOptions will result in an error.
2. Currently, we use enhanced-resolve internally to replace esbuild's resolve algorithm, so modifying esbuild resolve-related configurations is invalid. We plan to switch back in the future.

:::

## externalHelpers

By default, the output JS code may depend on helper functions to support the target environment or output format, and these helper functions will be inlined in the file that requires it.

With this configuration, the code will be converted using SWC, it will inline helper functions to import them from the external module `@swc/helpers`.

- **Type**: `boolean`
- **Default**: `false`

Below is a comparison of the output file changes before and after using this configuration.

Before enable:

```js title="./dist/index.js"
// helper function
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  // ...
}
// helper function
function _async_to_generator(fn) {
  return function () {
    // use asyncGeneratorStep
    // ...
  };
}

// your code
export var yourCode = function () {
  // use _async_to_generator
};
```

After enabled:

```js title="./dist/index.js"
// helper functions imported from @swc/helpers
import { _ as _async_to_generator } from '@swc/helpers/_/_async_to_generator';

// your code
export var yourCode = function () {
  // use _async_to_generator
};
```

## externals

Configure external dependencies that will not be bundled into the final bundle.

- **Type**:

```ts
type External = (string | RegExp)[];
```

- **Default**: `[]`
- **Build Type**: `Only supported for buildType: 'bundle'`
- **Example**:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    // do not bundle React
    externals: ['react'],
  },
});
```

## footer

Same as the [banner](#banner) configuration for adding a comment at the end of the output file.

## format

Used to set the output format of JavaScript files. The options `iife` and `umd` only take effect when `buildType` is `bundle`.

- **Type**: `'esm' | 'cjs' | 'iife' | 'umd'`
- **Default**: `cjs`

### format: esm

`esm` stands for "ECMAScript module" and requires the runtime environment to support import and export syntax.

- **Example**:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    format: 'esm',
  },
});
```

### format: cjs

`cjs` stands for "CommonJS" and requires the runtime environment to support exports, require, and module syntax. This format is commonly used in Node.js environments.

- **Example**:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    format: 'cjs',
  },
});
```

### format: iife

`iife` stands for "immediately-invoked function expression" and wraps the code in a function expression to ensure that any variables in the code do not accidentally conflict with variables in the global scope. This format is commonly used in browser environments.

- **Example**:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    format: 'iife',
  },
});
```

### format: umd

`umd` stands for "Universal Module Definition" and is used to run modules in different environments such as browsers and Node.js. Modules in UMD format can be used in various environments, either as global variables or loaded as modules using module loaders like RequireJS.

- **Example**:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    format: 'umd',
  },
});
```

## hooks

Build lifecycle hooks that allow custom logic to be injected at specific stages of the build process.

- **Types**:

```ts
type HookList = {
  name: string;
  apply: (compiler: ICompiler) => void;
  applyAfterBuiltIn?: boolean;
};
```

- **Default**: `[]`.

We can get the compiler instance in the apply method, modify its properties, and execute custom logic at different stages. For more information on Hooks, see [Using Hooks to Intervene in the Build Process](see [Using Hooks to Intervene in the Build Process]).
For more information on Hooks, see [Using-hooks-to-intervene-in-the-build-process](/guide/advance/in-depth-about-build.html#using-hooks-to-intervene-in-the-build-process).

```ts title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    buildType: 'bundle',
    hooks: [
      {
        name: 'renderChunk',
        apply: compiler => {
          // any logic for compiler
          compiler.hooks.renderChunk.tapPromise(
            { name: 'renderChunk' },
            async chunk => {
              return chunk;
            },
          );
        },
      },
    ],
  },
});
```

## input

Specify the entry file for the build, in the form of an array that can specify the directory

- **Type**:

```ts
type Input =
  | string[];
  | {
      [name: string]: string;
    }
```

- **Default**: `['src/index.ts']` in `bundle` mode, `['src']` in `bundleless` mode

**Array usage:**

In `bundle` mode, the following configurations will be built using `src/index.ts` and `src/index2.ts` as entry points. The `bundle` mode does not support configuring `input` as a directory.

```js title="modern.config.ts"
export default {
  buildConfig: {
    buildType: 'bundle',
    input: ['src/index.ts', 'src/index2.ts'],
  },
};
```

In `bundleless` mode, the following configuration compiles both files in the `src/a` directory and `src/index.ts` file.

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    buildType: 'bundleless',
    input: ['src/a', 'src/index.ts'],
  },
});
```

In `bundleless` mode, **Array usage** also supports the usage of `!` to filter partial files:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    buildType: 'bundleless',
    input: ['src', '!src/*.spec.ts'],
  },
});
```

The above configuration will build the files in the `src` directory, and will also filter files with the `spec.ts` suffix.This is useful in cases where the test files are in the same root directory as the source files.

**Object usage:**

When you need to modify the output file name in bundle mode, you can use an object configuration.

**The key of the object is the file name of the output, and the value is the file path of the source code.**

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    format: 'esm',
    input: {
      'index.esm': './src/index.ts',
    },
  },
});
```

## jsx

Specify the compilation method for JSX, which by default supports React 17 and higher versions and automatically injects JSX runtime code.

- **Type**: `automatic | transform`
- **Default**: `automatic`

If you need to support React 16, you can set `jsx` to `transform`:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    jsx: 'transform',
  },
});
```

:::tip
If you don't need to convert JSX, you can set `jsx` to `preserve`, but don't [use swc](/guide/advance/in-depth-about-build#use-swc) to do the code conversion.
For more information about JSX Transform, you can refer to the following links:

- [React Blog - Introducing the New JSX Transform](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html).
- [esbuild - JSX](https://esbuild.github.io/api/#jsx).

:::

## loader

**Experimental**

This option is used to change the interpretation method of the given input file.
For example, you need to handle the js file as jsx.

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    loader: {
      '.js': 'jsx',
    },
  },
});
```

## metafile

This option is used for build analysis. When enabled, esbuild will generate metadata about the build in JSON format.

- **Type**: `boolean`
- **Default**: `false`
- **Build Type**: `Only supported for buildType: 'bundle'`

To enable `metafile` generation:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    buildType: 'bundle',
    metafile: true,
  },
});
```

After executing the build, a `metafile-[xxx].json` file will be generated in the output directory. You can use tools like [esbuild analyze](https://esbuild.github.io/analyze/) and [bundle-buddy](https://bundle-buddy.com/esbuild) for visual analysis.

## minify

Use esbuild or terser to compress code, also pass [terserOptions](https://github.com/terser/terser#minify-options)

- **Type**: `'terser' | 'esbuild' | false | object`
- **Default**: `false`

```js title="modern.config.ts"
export default {
  buildConfig: {
    minify: {
      compress: {
        drop_console: true,
      },
    },
  },
};
```

## outDir

Specifies the output directory of the build.

- **Type**: `string`
- **Default**: `./dist`

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    outDir: './dist/esm',
  },
});
```

## platform

Generates code for the node environment by default, you can also specify `browser` which will generate code for the browser environment.
See [esbuild.platform](https://esbuild.github.io/api/#platform) learn more.

- **Type**: `'browser' | 'node'`
- **Default**: `'node'`

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    platform: 'browser',
  },
});
```

## redirect

In **`buildType: 'bundleless'`** build mode, the reference path is redirected to ensure that it points to the correct product, e.g:

- `import '. /index.less'` will be rewritten to `import '. /index.css'`
- `import icon from '. /close.svg'` would be rewritten as `import icon from '... /asset/close.svg'` to `import icon from '. /asset/close.svg'` (depending on the situation)
- `import * from './utils'` will be rewritten to `import * from './utils.mjs'` (if generate utils.mjs, depending on the situation)

In some scenarios, you may not need these functions, then you can turn it off with this configuration, and its reference path will not be changed after turning it off.

```js title="modern.config.ts"
export default {
  buildConfig: {
    redirect: {
      alias: false, // Turn off modifying alias paths
      style: false, // Turn off modifying the path to the style file
      asset: false, // Turn off modifying the path to the asset
      autoExtension: false, // Turn off modifying the suffix to the js file
    },
  },
};
```

## resolve

Custom module resolution options

### resolve.alias

The basic usage is the same as [alias](#alias).

The issue with [alias](#alias) is that we incorrectly handled Module IDs in a bundleless scenario:

```js
import { createElement } from 'react';
```

When we configure alias: `{ react: 'react-native' }`, the result becomes:

```js
import { createElement } from './react-native';
```

A Module ID is incorrectly processed as a relative path, which is not expected.

We want to fix this issue, but it may break existing projects.

Therefore, in **MAJOR_VERSION.58.0**, we provided `resolve.alias` to solve this problem. Additionally, `resolve.alias` removed the default value `{ "@": "./src"}` provided by [alias](#alias).

If you need this feature, please use `resolve.alias`.

In the next major version, `resolve.alias` will replace [alias](#alias).

:::warning

- Note that this configuration should not be mixed with [alias](#alias).
- Ensure that this configuration specifies a relative path, such as `{ "@": "./src" }` rather than `{ "@": "src"}`.

:::

### resolve.mainFields

A list of fields in package.json to try when parsing the package entry point.

- **Type**: `string[]`
- **Default**: depends on [platform](#platform)
  - node: ['module', 'main']
  - browser: ['module', 'browser', 'main']
- **Version**: `>=MAJOR_VERSION.36.0`

For example, we want to load the `js:source` field first:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    resolve: {
      mainFields: ['js:source', 'module', 'main'],
    },
  },
});
```

:::warning
`resolve.mainFields` has a lower priority than the exports field in package.json, and if an entry point is successfully resolved from exports, `resolve.mainFields` will be ignored.
:::

### resolve.jsExtentions

Support for implicit file extensions

- **Type**: `string[]`
- **Default**: `['.jsx', '.tsx', '.js', '.ts', '.json']`
- **Version**: `>=MAJOR_VERSION.36.0`

Do not use implicit file extensions for css files, currently Module only supports ['.less', '.css', '.sass', '.scss'] suffixes.

Node's parsing algorithm does not consider `.mjs` and `cjs` as implicit file extensions, so they are not included here by default, but can be included by changing this configuration:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    resolve: {
      jsExtentions: ['.mts', 'ts'],
    },
  },
});
```

### resolve.tsconfig

Used to configure enhanced-resolve in [tsconfig-paths-webpack-plugin](https://www.npmjs.com/package/tsconfig-paths-webpack-plugin) to support resolution of alias in tsconfig.json and nested `@` alias conflicts.

- **Type**:

```ts
type Tsconfig = {
  configFile: string;
  references?: string[] | undefined;
};
```

- **Default**: `{ configFile: './tsconfig.json', references: undefined }`
- **Version**: `>=MAJOR_VERSION.61.1`

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    resolve: {
      tsConfig: {
        configFile: './tsconfig.json',
      },
    },
  },
});
```

## shims

When building CommonJS/ESM artifacts, inject some polyfill code such as `__dirname` which can only be used in CommonJS.
After enable this option, it will compile `__dirname` as `path.dirname(fileURLToPath(import.meta.url))` when format is esm.

See details [here](https://github.com/web-infra-dev/modern.js/blob/main/packages/solutions/module-tools/shims),
Note that esm shims will only be injected if [platform](#platform) is node, because the url module is used.

- **Type**: `boolean`
- **Default**: `false`
- **Version**: `>=MAJOR_VERSION.38.0`

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    shims: true,
  },
});
```

## sideEffects

Module sideEffects

- **Type**: `RegExg[] | (filePath: string, isExternal: boolean) => boolean | boolean`
- **Default**: `undefined`

Normally, we configure the module's side effects via the sideEffects field in package.json, but in some cases, The package.json of a third-party package is unreliable.Such as when we reference a third-party package style file

```js
import 'other-package/dist/index.css';
```

But the package.json of this third-party package does not have the style file configured in the sideEffects

```json title="other-package/package.json"
{
  "sideEffects": ["dist/index.js"]
}
```

At the same time you set [style.inject](#styleinject) to `true` and you will see a warning message like this in the console

```bash
[LIBUILD:ESBUILD_WARN] Ignoring this import because "other-package/dist/index.css" was marked as having no side effects
```

At this point, you can use this configuration option to manually configure the module's `"sideEffects"` to support regular and functional forms.

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    sideEffects: [/\.css$/],
    // or
    // sideEffects: (filePath, isExternal) => /\.css$/.test(filePath),
  },
});
```

:::tip
After adding this configuration, the sideEffects field in package.json will no longer be read when packaging
:::

## sourceDir

Specify the source directory of the build, default is `src`, which is used to generate the corresponding output directory based on the source directory structure when building `bundleless`.
Same as [esbuild.outbase](https://esbuild.github.io/api/#outbase).

- **Type**: `string`
- **Default**: `src`

## sourceMap

Whether to generate sourceMap or not

- **Type**: `boolean | 'inline' | 'external'`
- **Default**: `false`

## sourceType

Sets the format of the source code. By default, the source code will be treated as EsModule. When the source code is using CommonJS, you need to set `commonjs`.

- **Type**: `'commonjs' | 'module'`
- **Default**: `'module'`

## splitting

Whether to enable code splitting.
Only support [format: 'esm'](#format-esm) and [format: 'cjs'](#format-cjs),see [esbuild.splitting](https://esbuild.github.io/api/#splitting) learn more.

- **Type**: `boolean`
- **Default**: `false`

## style

Configure style-related configuration

## style.less

less-related configuration

## style.less.lessOptions

Refer to [less](https://less.bootcss.com/usage/#less-options) for detailed configuration

- **Type**: `object`
- **Default**: `{ javascriptEnabled: true }`

## style.less.additionalData

Add `Less` code to the beginning of the entry file.

- **Type**: `string`
- **Default**: `undefined`

```js title="modern.config.ts"
export default {
  buildConfig: {
    style: {
      less: {
        additionalData: `@base-color: #c6538c;`,
      },
    },
  },
};
```

## style.less.implementation

Configure the implementation library used by `Less`, if not specified, the built-in version used is `4.1.3`.

- **Type**: `string | object`
- **Default**: `undefined`

Specify the implementation library for `Less` when the `object` type is specified.

```js title="modern.config.ts"
export default {
  buildConfig: {
    style: {
      less: {
        implementation: require('less'),
      },
    },
  },
};
```

For the `string` type, specify the path to the implementation library for `Less`

```js title="modern.config.ts"
export default {
  buildConfig: {
    style: {
      less: {
        implementation: require.resolve('less'),
      },
    },
  },
};
```

## style.sass

sass-related configuration.

## style.sass.sassOptions

Refer to [node-sass](https://github.com/sass/node-sass#options) for detailed configuration.

- **Type**: `object`
- **Default**: `{}`

## style.sass.additionalData

Add `Sass` code to the beginning of the entry file.

- **Type**: `string | Function`
- **Default**: `undefined`

```js title="modern.config.ts"
export default {
  buildConfig: {
    style: {
      sass: {
        additionalData: `$base-color: #c6538c;
          $border-dark: rgba($base-color, 0.88);`,
      },
    },
  },
};
```

## style.sass.implementation

Configure the implementation library used by `Sass`, the built-in version used is `1.54.4` if not specified.

- **Type**: `string | object`
- **Default**: `undefined`

Specify the implementation library for `Sass` when the `object` type is specified.

```js title="modern.config.ts"
export default {
  buildConfig: {
    style: {
      sass: {
        implementation: require('sass'),
      },
    },
  },
};
```

For the `string` type, specify the path to the `Sass` implementation library

```js title="modern.config.ts"
export default {
  buildConfig: {
    style: {
      sass: {
        implementation: require.resolve('sass'),
      },
    },
  },
};
```

## style.postcss

Used to configure options for PostCSS. The provided values will be merged with the default configuration using `Object.assign`. Note that `Object.assign` performs a shallow copy, so it will completely override the built-in `plugins` array.

For detailed configuration, please refer to [PostCSS](https://github.com/postcss/postcss#options).

- **Type**:

```ts
type PostcssOptions = {
  processOptions?: ProcessOptions;
  plugins?: AcceptedPlugin[];
};
```

- **Default**:

```ts
const defaultConfig = {
  plugins: [
    // The following plugins are enabled by default
    require('postcss-flexbugs-fixes'),
    require('postcss-media-minmax'),
    require('postcss-nesting'),
    // The following plugins are only enabled when the target is `es5`
    require('postcss-custom-properties'),
    require('postcss-initial'),
    require('postcss-page-break'),
    require('postcss-font-variant'),
  ],
};
```

- **Example**:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    style: {
      postcss: {
        plugins: [yourPostCSSPlugin],
      },
    },
  },
});
```

## style.inject

Configure whether to insert CSS styles into JavaScript code in bundle mode.

- **Type**: `boolean`
- **Default**: `false`

Set `inject` to `true` to enable this feature:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    style: {
      inject: true,
    },
  },
});
```

Once enabled, you will see the CSS code referenced in the source code included in the bundled JavaScript output.

For example, if you write `import './index.scss'` in the source code, you will see the following code in the output:

```js title="dist/index.js"
// node_modules/style-inject/dist/style-inject.es.js
function styleInject(css, ref) {
  // ...
}
var style_inject_es_default = styleInject;

// src/index.scss
var css_248z = '.body {\n color: black;\n}';
style_inject_es_default(css_248z);
```

:::tip

After enabling `inject`, you need to pay attention to the following points:

- `@import` in CSS files will not be processed. If your CSS file contains `@import`, you need to manually import the CSS file in the JS file (less and scss files are not required because they have preprocessing).
- Consider the impact of `sideEffects`. By default, our builder assumes that CSS has side effects. If the `sideEffects` field is set in your project or third-party package's package.json and does not include this CSS file, you will receive a warning:

```shell
[LIBUILD:ESBUILD_WARN] Ignoring this import because "src/index.scss" was marked as having no side effects by plugin "libuild:adapter"
```

You can resolve this by configuring [sideEffects](#sideeffects).

:::

## style.autoModules

Enable CSS Modules automatically based on the filename.

- **Type**: `boolean | RegExp`
- **Default**: `true`

`true` : Enables CSS Modules for style files ending with `.module.css` `.module.less` `.module.scss` `.module.sass` filenames

`false` : Disable CSS Modules.

`RegExp` : Enables CSS Modules for all files that match the regular condition.

## style.modules

CSS Modules configuration

- **Type**: `object`
- **Default**: `{}`

A common configuration is `localsConvention`, which changes the class name generation rules for css modules

```js title="modern.config.ts"
export default {
  buildConfig: {
    style: {
      modules: {
        localsConvention: 'camelCaseOnly',
      },
    },
  },
};
```

For the following styles

```css
.box-title {
  color: red;
}
```

You can use `styles.boxTitle` to access

For detailed configuration see [postcss-modules](https://github.com/madyankin/postcss-modules#usage)

## style.tailwindcss

Used to modify the configuration of [Tailwind CSS](https://tailwindcss.com/docs/configuration).

- **Type**: `object | Function`
- **Default**:

```js title="modern.config.ts"
const tailwind = {
  content: ['./src/**/*.{js,jsx,ts,tsx}', './config/html/**/*.{html,ejs,hbs}'],
};
```

### Enabling Tailwind CSS

Before using `style.tailwindcss`, you need to enable the Tailwind CSS plugin for Modern.js Module.

Please refer to the section [Using Tailwind CSS](/guide/best-practices/use-tailwindcss.html) for instructions on how to enable it.

### Type

When the value is of type `object`, it is merged with the default configuration via `Object.assign`.

When the value is of type `Function`, the object returned by the function is merged with the default configuration via `Object.assign`.

The rest of the usage is the same as Tailwind CSS: [Quick Portal](https://tailwindcss.com/docs/configuration).

### Notes

Please note that:

- If you are using both the `tailwind.config.{ts,js}` file and `tools.tailwindcss` option, the configuration defined in `tools.tailwindcss` will take precedence and override the content defined in `tailwind.config.{ts,js}`.
- If you are using the `designSystem` configuration option simultaneously, the `theme` configuration of Tailwind CSS will be overridden by the value of `designSystem`.

The usage of other configurations follows the same approach as the official usage of Tailwind CSS. Please refer to [tailwindcss - Configuration](https://tailwindcss.com/docs/configuration) for more details.

## target

`target` is used to set the target environment for the generated JavaScript code. It enables Modern.js Module to transform JavaScript syntax that is not recognized by the target environment into older versions of JavaScript syntax that are compatible with these environments.

- **Type**:

```ts
type Target =
  | 'es5'
  | 'es6'
  | 'es2015'
  | 'es2016'
  | 'es2017'
  | 'es2018'
  | 'es2019'
  | 'es2020'
  | 'es2021'
  | 'es2022'
  | 'esnext';
```

- **Default**: `'es6'`

For example, compile the code to `es5` syntax:

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    target: 'es5',
  },
});
```

## transformImport

Using [SWC](https://swc.rs/) provides the same ability and configuration as [`babel-plugin-import`](https://github.com/umijs/babel-plugin-import).
With this configuration, the code will be converted using SWC.

- **Type**: `object[]`
- **Default**: `[]`

The elements of the array are configuration objects for `babel-plugin-import`, which can be referred to [options](https://github.com/umijs/babel-plugin-import#options)。

**Example:**

```ts title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    transformImport: [
      // babel-plugin-import`s options config
      {
        libraryName: 'foo',
        style: true,
      },
    ],
  },
});
```

Reference the [Import Plugin - Notes](plugins/official-list/plugin-import.html#notes)

## transformLodash

Specifies whether to modularize the import of [lodash](https://www.npmjs.com/package/lodash) and remove unused lodash modules to reduce the code size of lodash.

This optimization is implemented using [babel-plugin-lodash](https://www.npmjs.com/package/babel-plugin-lodash) and [swc-plugin-lodash](https://github.com/web-infra-dev/swc-plugins/tree/main/crates/plugin_lodash) under the hood.

With this configuration, the code will be converted using SWC.

- **Type**: `boolean`
- **Default**: `false`

When you enable this, Modern.js Module will automatically redirects the code references of `lodash` to sub-paths.

For example:

```ts title="input.js"
import _ from 'lodash';
import { add } from 'lodash/fp';

const addOne = add(1);
_.map([1, 2, 3], addOne);
```

The transformed code will be:

```ts title="output.js"
import _add from 'lodash/fp/add';
import _map from 'lodash/map';

const addOne = _add(1);
_map([1, 2, 3], addOne);
```

## tsconfig

Path to the tsconfig file

- **Type**: `string`
- **Default**: `tsconfig.json`
- **Version**: `>=MAJOR_VERSION.36.0`

```js title="modern.config.ts"
export default defineConfig({
  buildConfig: {
    tsconfig: 'tsconfig.build.json',
  },
});
```

## umdGlobals

Specify global variables for external import of umd artifacts

- **Type**: `Record<string, string>`
- **Default**: `{}`

```js title="modern.config.ts"
export default {
  buildConfig: {
    umdGlobals: {
      react: 'React',
      'react-dom': 'ReactDOM',
    },
  },
};
```

At this point, `react` and `react-dom` will be seen as global variables imported externally and will not be packed into the umd product, but will be accessible by way of `global.React` and `global.ReactDOM`

## umdModuleName

Specifies the module name of the umd product

- **Type**: `string | Function`
- **Default**: `name => name`

```js
export default {
  buildConfig: {
    format: 'umd',
    umdModuleName: 'myLib',
  },
};
```

At this point the umd artifact will go to mount on `global.myLib`

:::tip

- The module name of the umd artifact must not conflict with the global variable name.
- Module names will be converted to camelCase, e.g. `my-lib` will be converted to `myLib`, refer to [toIdentifier](https://github.com/babel/babel/blob/main/packages/babel-types/src/converters/toIdentifier.ts).
  :::

Also the function form can take one parameter, which is the output path of the current package file

```js title="modern.config.ts"
export default {
  buildConfig: {
    format: 'umd',
    umdModuleName: path => {
      if (path.includes('index')) {
        return 'myLib';
      } else {
        return 'myLib2';
      }
    },
  },
};
```
