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:

alias

  • Type: Record<string, string> | Function
  • Default: {'@': 'src',}
TIP

For TypeScript projects, you only need to configure compilerOptions.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.

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.

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.

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.

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:

modern.config.ts
export default defineConfig({
  buildConfig: {
    asset: {
      limit: 0,
    },
  },
});

asset.path

Static resource output path, will be based on outDir

  • Type: string
  • Default: assets

asset.publicPath

The CDN prefix given to unlinked assets when bundling.

  • Type: string
  • Default: undefined
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, 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.

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:

your-app-env.d.ts
declare module '*.svg' {
  const src: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
  export default src;
}
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:

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 and type.

  • Type: boolean
  • Default: false
  • Version: >=2.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.

Notice 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'

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:

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.

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

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

interface BannerAndFooter {
  js?: string;
  css?: string;
  dts?: string;
}
  • Type: BannerAndFooter
  • Default: {}
  • Version: >=2.36.0

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

import { moduleTools, defineConfig } from '@edenx/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: []
export default {
  buildConfig: {
    copy: [{ from: '. /src/assets', to: '' }],
  },
};

Reference for array settings: copy-webpack-plugin patterns

copy.patterns

  • Type: CopyPattern[]
  • Default: []
interface CopyPattern {
  from: string;
  to?: string;
  context?: string;
  globOptions?: globby.GlobbyOptions;
}

copy.options

  • Type:
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 by default, instead of fs.copy.

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 using esbuildOptions configuration.

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.

env.d.ts
declare const YOUR_ADD_GLOBAL_VAR;

You can also replace environment variable:

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.

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

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

// 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:
{
  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:

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

  • Type: string
  • Default: ./

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

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 > 2.43.0,In fact, we experimentally enabled this option in the 2.42.0 version, but the many problems it brought forced us to enable it dynamically.

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: >2.43.0
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
modern.config.ts
export default defineConfig({
  buildConfig: {
    dts: {
      only: true,
    },
  },
});

dts.tsconfigPath

deprecated,use tsconfig instead.

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

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.

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
modern.config.ts
export default defineConfig({
  buildConfig: {
    dts: {
      respectExternal: false,
    },
  },
});

esbuildOptions

Used to modify the esbuild configuration.

  • 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:

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

For example, register an esbuild plugin:

modern.config.ts
import { myEsbuildPlugin } from './myEsbuildPlugin';

export default defineConfig({
  buildConfig: {
    esbuildOptions: options => {
      options.plugins = [myEsbuildPlugin, ...options.plugins];
      return options;
    },
  },
});

When adding an esbuild plugin, please note that you need to add the plugin at the beginning of the plugins array. This is because the Modern.js Module is also integrated into the entire build process through an esbuild plugin. Therefore, custom plugins need to be registered with higher priority.

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:

./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:

./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:
type External = (string | RegExp)[];
  • Default: []
  • Build Type: Only supported for buildType: 'bundle'
  • Example:
modern.config.ts
export default defineConfig({
  buildConfig: {
    // do not bundle React
    externals: ['react'],
  },
});

Same as the 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:
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:
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:
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:
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:
type HookList = {
  name: string;
  apply: (compiler: ICompiler) => void.
}
  • 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.

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:
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.

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.

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:

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.

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:

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 to do the code conversion. For more information about JSX Transform, you can refer to the following links:

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:

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 and bundle-buddy for visual analysis.

minify

Use esbuild or terser to compress code, also pass terserOptions

  • Type: 'terser' | 'esbuild' | false | object
  • Default: false
modern.config.ts
export default {
  buildConfig: {
    minify: {
      compress: {
        drop_console: true,
      },
    },
  },
};

outDir

Specifies the output directory of the build.

  • Type: string
  • Default: ./dist
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 learn more.

  • Type: 'browser' | 'node'
  • Default: 'node'
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.

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.mainFields

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

  • Type: string[]
  • Default: depends on platform
    • node: ['module', 'main']
    • browser: ['module', 'browser', 'main']
  • Version: >=2.36.0

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

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: >=2.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:

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

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, Note that esm shims will only be injected if platform is node, because the url module is used.

  • Type: boolean
  • Default: false
  • Version: >=2.38.0
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

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

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

At the same time you set style.inject to true and you will see a warning message like this in the console

[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.

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.

  • 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' and format: 'cjs',see esbuild.splitting learn more.

  • Type: boolean
  • Default: false

style

Configure style-related configuration

style.less

less-related configuration

style.less.lessOptions

Refer to less 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
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.

modern.config.ts
export default {
  buildConfig: {
    style: {
      less: {
        implementation: require('less'),
      },
    },
  },
};

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

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

style.sass

sass-related configuration.

style.sass.sassOptions

Refer to node-sass for detailed configuration.

  • Type: object
  • Default: {}

style.sass.additionalData

Add Sass code to the beginning of the entry file.

  • Type: string | Function
  • Default: undefined
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.5.4 if not specified.

  • Type: string | object
  • Default: undefined

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

modern.config.ts
export default {
  buildConfig: {
    style: {
      sass: {
        implementation: require('sass'),
      },
    },
  },
};

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

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.

  • Type:
type PostcssOptions = {
  processOptions?: ProcessOptions;
  plugins?: AcceptedPlugin[];
};
  • Default:
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:
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:

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:

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:
[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.

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

modern.config.ts
export default {
  buildConfig: {
    style: {
      modules: {
        localsConvention: 'camelCaseOnly',
      },
    },
  },
};

For the following styles

.box-title {
  color: red;
}

You can use styles.boxTitle to access

For detailed configuration see postcss-modules

style.tailwindcss

Used to modify the configuration of Tailwind CSS.

  • Type: object | Function
  • Default:
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 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.

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 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:
type Target =
  | 'es5'
  | 'es6'
  | 'es2015'
  | 'es2016'
  | 'es2017'
  | 'es2018'
  | 'es2019'
  | 'es2020'
  | 'es2021'
  | 'es2022'
  | 'esnext';
  • Default: 'es6'

For example, compile the code to es5 syntax:

modern.config.ts
export default defineConfig({
  buildConfig: {
    target: 'es5',
  },
});

transformImport

Using SWC provides the same ability and configuration as 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

Example:

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

Reference the Import Plugin - Notes

transformLodash

Specifies whether to modularize the import of lodash and remove unused lodash modules to reduce the code size of lodash.

This optimization is implemented using babel-plugin-lodash and swc-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:

input.js
import _ from 'lodash';
import { add } from 'lodash/fp';

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

The transformed code will be:

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: >=2.36.0
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: {}
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
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. :::

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

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