buildConfig is a configuration option that describes how to compile and generate build artifacts. It contains all the configurations related to the build process.
object | object[]Before start using buildConfig, please read the following documentation to understand its purpose:
Record<string, string> | Function{'@': 'src',}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.
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.
It is also possible to return a new object as the final result in the function, which will override the pre-defined alias object.
Contains configuration related to static assets.
Static resource output file name.
string | ((assetPath) => name)[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.
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.
number10 * 1024For example, set limit to 0 to avoid assets inlining:
Static resource output path, will be based on outDir
stringassetsThe CDN prefix given to unlinked assets when bundling.
stringundefinedAt this point, all static assets will be prefixed with https://xxx/.
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
boolean | objectfalseWhen svgr feature is enabled, you can use svg as a component using the default export.
:::
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:
Set the matching svg file
string | RegExp | (string | RegExp)[]/\.svg$/Set unmatched svg files
string | RegExp | (string | RegExp)[]undefinedUsed to configure the SVG export type when using SVGR.
'named' | 'default'defaultwhen it is 'named', use the following syntax:
The named export defaults to ReactComponent, and can be customized with the asset.svgr.namedExport.
Suffixes for js files and type description files in automation based on format and type.
booleanfalse>=2.38.0When 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.
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'
Automatically externalize project dependencies and peerDependencies and not package them into the final bundle
boolean | objecttrueWhen we want to turn off the default handling behavior for third-party dependencies, we can do so by:
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.
Whether or not the dep dependencies of the external project are needed
booleantrueWhether to require peerDep dependencies for external projects
booleantrueProvides the ability to inject content into the top and bottom of each JS , CSS and DTS file.
BannerAndFooter{}>=2.36.0Let's say you want to add copyright information to JS and CSS files.
The build type, bundle will package your code, bundleless will only do the code conversion
'bundle' | 'bundleless''bundle'Copies the specified file or directory into the build output directory
object[][]Reference for array settings: copy-webpack-plugin patterns
Refer to Use the Copy Tools for the complete usage of the copy option.
CopyPattern[][]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 global variables that will be injected into the code
Record<string, string>{}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.
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.
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.tsfile does not exist, then you can create it manually.
You can also replace environment variable:
With the above configuration, we can put the following code.
When executing VERSION=1.0.0 modern build, the conversion is:
To prevent excessive global replacement substitution, it is recommended that the following two principles be followed when using
The dts file generates the relevant configuration, by default it generates.
false | objectWhether to allow the build to succeed if a type error occurs.
booleantrueBy 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:
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.
The output path of the dts file, based on outDir
string./For example, output to the types directory under the outDir:
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.
booleanfalse>2.43.0Whether to generate only type files during the build process without generating JavaScript output files.
booleanfalsedeprecated,use tsconfig instead.
Specifies the path to the tsconfig file used to generate the type file.
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.
booleantrueUsed to modify the esbuild configuration.
FunctionOnly supported for buildType: 'bundle'c => cFor example, if we need to modify the file extension of the generated files:
For example, register an esbuild plugin:
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.
We have done many extensions based on the original esbuild build. Therefore, when using this configuration, pay attention to the following:
target: 'es5', but we support this scenario internally using SWC. Setting target: 'es5' through esbuildOptions will result in an error.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.
booleanfalseBelow is a comparison of the output file changes before and after using this configuration.
Before enable:
After enabled:
Configure external dependencies that will not be bundled into the final bundle.
[]Only supported for buildType: 'bundle'Same as the banner configuration for adding a comment at the end of the output file.
Used to set the output format of JavaScript files. The options iife and umd only take effect when buildType is bundle.
'esm' | 'cjs' | 'iife' | 'umd'cjsesm stands for "ECMAScript module" and requires the runtime environment to support import and export syntax.
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.
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.
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.
Build lifecycle hooks that allow custom logic to be injected at specific stages of the build process.
[].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.
Specify the entry file for the build, in the form of an array that can specify the directory
['src/index.ts'] in bundle mode, ['src'] in bundleless modeArray 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.
In bundleless mode, the following configuration compiles both files in the src/a directory and src/index.ts file.
In bundleless mode, Array usage also supports the usage of ! to filter partial files:
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.
Specify the compilation method for JSX, which by default supports React 17 and higher versions and automatically injects JSX runtime code.
automatic | transformautomaticIf you need to support React 16, you can set jsx to transform:
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:
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.
This option is used for build analysis. When enabled, esbuild will generate metadata about the build in JSON format.
booleanfalseOnly supported for buildType: 'bundle'To enable metafile generation:
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.
Use esbuild or terser to compress code, also pass terserOptions
'terser' | 'esbuild' | false | objectfalseSpecifies the output directory of the build.
string./distGenerates 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.
'browser' | 'node''node'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.
Custom module resolution options
The basic usage is the same as alias.
The issue with alias is that we incorrectly handled Module IDs in a bundleless scenario:
When we configure alias: { react: 'react-native' }, the result becomes:
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 2.58.0, we provided resolve.alias to solve this problem. Additionally, resolve.alias removed the default value { "@": "./src"} provided by alias.
If you need this feature, please use resolve.alias.
In the next major version, resolve.alias will replace alias.
{ "@": "./src" } rather than { "@": "src"}.A list of fields in package.json to try when parsing the package entry point.
string[]>=2.36.0For example, we want to load the js:source field first:
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.
Support for implicit file extensions
string[]['.jsx', '.tsx', '.js', '.ts', '.json']>=2.36.0Do 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:
Used to configure enhanced-resolve in tsconfig-paths-webpack-plugin to support resolution of alias in tsconfig.json and nested @ alias conflicts.
{ configFile: './tsconfig.json', references: undefined }>=2.61.1When 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.
booleanfalse>=2.38.0Module sideEffects
RegExg[] | (filePath: string, isExternal: boolean) => boolean | booleanundefinedNormally, 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
But the package.json of this third-party package does not have the style file configured in the sideEffects
At the same time you set style.inject to true and you will see a warning message like this in the console
At this point, you can use this configuration option to manually configure the module's "sideEffects" to support regular and functional forms.
After adding this configuration, the sideEffects field in package.json will no longer be read when packaging
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.
stringsrcWhether to generate sourceMap or not
boolean | 'inline' | 'external'falseSets 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.
'commonjs' | 'module''module'Whether to enable code splitting. Only support format: 'esm' and format: 'cjs',see esbuild.splitting learn more.
booleanfalseConfigure style-related configuration
less-related configuration
Refer to less for detailed configuration
object{ javascriptEnabled: true }Add Less code to the beginning of the entry file.
stringundefinedConfigure the implementation library used by Less, if not specified, the built-in version used is 4.1.3.
string | objectundefinedSpecify the implementation library for Less when the object type is specified.
For the string type, specify the path to the implementation library for Less
sass-related configuration.
Refer to node-sass for detailed configuration.
object{}Add Sass code to the beginning of the entry file.
string | FunctionundefinedConfigure the implementation library used by Sass, the built-in version used is 1.54.4 if not specified.
string | objectundefinedSpecify the implementation library for Sass when the object type is specified.
For the string type, specify the path to the Sass implementation library
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.
Configure whether to insert CSS styles into JavaScript code in bundle mode.
booleanfalseSet inject to true to enable this feature:
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:
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).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:You can resolve this by configuring sideEffects.
Enable CSS Modules automatically based on the filename.
boolean | RegExptruetrue : 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.
CSS Modules configuration
object{}A common configuration is localsConvention, which changes the class name generation rules for css modules
For the following styles
You can use styles.boxTitle to access
For detailed configuration see postcss-modules
Used to modify the configuration of Tailwind CSS.
object | FunctionBefore 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.
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.
Please note that:
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}.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 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.
'es6'For example, compile the code to es5 syntax:
Using SWC provides the same ability and configuration as babel-plugin-import.
With this configuration, the code will be converted using SWC.
object[][]The elements of the array are configuration objects for babel-plugin-import, which can be referred to options。
Example:
Reference the Import Plugin - Notes
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.
booleanfalseWhen you enable this, Modern.js Module will automatically redirects the code references of lodash to sub-paths.
For example:
The transformed code will be:
Path to the tsconfig file
stringtsconfig.json>=2.36.0Specify global variables for external import of umd artifacts
Record<string, string>{}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
Specifies the module name of the umd product
string | Functionname => nameAt this point the umd artifact will go to mount on global.myLib
:::tip
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