Project Icon

esbuild-loader

使用 esbuild 加速 Webpack 构建的高性能工具

esbuild-loader 是一款基于 esbuild 的 Webpack 插件,可显著提高 JavaScript 和 TypeScript 项目的构建速度。它支持快速的 ESNext 和 TypeScript 转译,以及高效的 JS 代码压缩,比 babel-loader 和 ts-loader 等传统加载器更快。esbuild-loader 配置简单,易于集成到现有 Webpack 项目中,能有效优化前端构建流程。


esbuild-loader

Speed up your Webpack build with esbuild! 🔥

esbuild is a JavaScript bundler written in Go that supports blazing fast ESNext & TypeScript transpilation and JS minification.

esbuild-loader lets you harness the speed of esbuild in your Webpack build by offering faster alternatives for transpilation (eg. babel-loader/ts-loader) and minification (eg. Terser)!

[!TIP] Are you using TypeScript with Node.js?

Supercharge your Node.js with TypeScript support using tsx!

tsx is a simple, lightweight, and blazing fast alternative to ts-node.

→ Learn more about tsx


Already a sponsor? Join the discussion in the Development repo!

🚀 Install

npm i -D esbuild-loader

🚦 Quick Setup

To leverage esbuild-loader in your Webpack configuration, add a new rule for esbuild-loader matching the files you want to transform, such as .js, .jsx, .ts, or .tsx. Make sure to remove any other loaders you were using before (e.g. babel-loader/ts-loader).

Here's an example of how to set it up in your webpack.config.js:

  module.exports = {
      module: {
          rules: [
-             // Transpile JavaScript
-             {
-                 test: /\.js$/,
-                 use: 'babel-loader'
-             },
-
-             // Compile TypeScript
-             {
-                 test: /\.tsx?$/,
-                 use: 'ts-loader'
-             },
+             // Use esbuild to compile JavaScript & TypeScript
+             {
+                 // Match `.js`, `.jsx`, `.ts` or `.tsx` files
+                 test: /\.[jt]sx?$/,
+                 loader: 'esbuild-loader',
+                 options: {
+                     // JavaScript version to compile to
+                     target: 'es2015'
+                 }
+             },

              // Other rules...
          ],
      },
  }

In this setup, esbuild will automatically determine how to handle each file based on its extension:

  • .js files will be treated as JS (no JSX allowed)
  • .jsx as JSX
  • .ts as TS (no TSX allowed)
  • .tsx as TSX

If you want to force a specific loader on different file extensions (e.g. to allow JSX in .js files), you can use the loader option:

 {
     test: /\.js$/,
     loader: 'esbuild-loader',
     options: {
+        // Treat `.js` files as `.jsx` files
+        loader: 'jsx',

         // JavaScript version to transpile to
         target: 'es2015'
     }
 }

Loader

JavaScript

esbuild-loader can be used in-place of babel-loader to transpile new JavaScript syntax into code compatible with older JavaScript engines.

While this ensures your code can run smoothly across various environments, note that it can bloat your output code (like Babel).

The default target is esnext, which means it doesn't perform any transpilations.

To specify a target JavaScript engine that only supports ES2015, use the following configuration in your webpack.config.js:

 {
     test: /\.jsx?$/,
     loader: 'esbuild-loader',
     options: {
+        target: 'es2015',
     },
 }

For a detailed list of supported transpilations and versions, refer to the esbuild documentation.

TypeScript

esbuild-loader can be used in-place of ts-loader to compile TypeScript.

{
    // `.ts` or `.tsx` files
    test: /\.tsx?$/,
    loader: 'esbuild-loader',
}

[!IMPORTANT] It's possible to use loader: 'tsx' for both .ts and .tsx files, but this could lead to unexpected behavior as TypeScript and TSX do not have compatible syntaxes.

→ Read more

tsconfig.json

If you have a tsconfig.json file in your project, esbuild-loader will automatically load it.

If it's under a custom name, you can pass in the path via tsconfig option:

 {
     test: /\.tsx?$/,
     loader: 'esbuild-loader',
     options: {
+        tsconfig: './tsconfig.custom.json',
     },
 },

Behind the scenes: get-tsconfig is used to load the tsconfig, and to also resolve the extends property if it exists.

The tsconfigRaw option can be used to pass in a raw tsconfig object, but it will not resolve the extends property.

Caveats
  • esbuild only supports a subset of tsconfig options (see TransformOptions interface).

  • Enable isolatedModules to avoid mis-compilation with features like re-exporting types.

  • Enable esModuleInterop to make TypeScript's type system compatible with ESM imports.

  • Features that require type interpretation, such as emitDecoratorMetadata and declaration, are not supported.

→ Read more about TypeScript Caveats

tsconfig.json Paths

Use tsconfig-paths-webpack-plugin to add support for tsconfig.json#paths.

Since esbuild-loader only transforms code, it cannot aid Webpack with resolving paths.

Type-checking

esbuild does not type check your code. And according to the esbuild FAQ, it will not be supported.

Consider these type-checking alternatives:

EsbuildPlugin

Minification

Esbuild supports JavaScript minification, offering a faster alternative to traditional JS minifiers like Terser or UglifyJs. Minification is crucial for reducing file size and improving load times in web development. For a comparative analysis of its performance, refer to these minification benchmarks.

In webpack.config.js:

+ const { EsbuildPlugin } = require('esbuild-loader')

  module.exports = {
      ...,

+     optimization: {
+         minimizer: [
+             new EsbuildPlugin({
+                 target: 'es2015'  // Syntax to transpile to (see options below for possible values)
+             })
+         ]
+     },
  }

[!TIP] Utilizing the target option allows for the use of newer JavaScript syntax, enhancing minification effectiveness.

Defining constants

Webpack's DefinePlugin can replaced with EsbuildPlugin to define global constants. This could speed up the build by removing the parsing costs associated with the DefinePlugin.

In webpack.config.js:

- const { DefinePlugin } = require('webpack')
+ const { EsbuildPlugin } = require('esbuild-loader')

  module.exports = {
      // ...,

      plugins:[
-         new DefinePlugin({
-             'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
-         })
+         new EsbuildPlugin({
+             define: {
+                 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
+             },
+         }),
      ]
  }

Transpilation

If your project does not use TypeScript, JSX, or any other syntax that requires additional configuration beyond what Webpack provides, you can use EsbuildPlugin for transpilation instead of the loader.

It will be faster because there's fewer files to process, and will produce a smaller output because polyfills will only be added once for the entire build as opposed to per file.

To utilize esbuild for transpilation, simply set the target option on the plugin to specify which syntax support you want.

CSS Minification

Depending on your setup, there are two ways to minify CSS. You should already have CSS loading setup using css-loader.

CSS assets

If the CSS is extracted and emitted as .css file, you can replace CSS minification plugins like css-minimizer-webpack-plugin with the EsbuildPlugin.

Assuming the CSS is extracted using something like MiniCssExtractPlugin, in webpack.config.js:

  const { EsbuildPlugin } = require('esbuild-loader')
  const MiniCssExtractPlugin = require('mini-css-extract-plugin');

  module.exports = {
      // ...,

      optimization: {
          minimizer: [
              new EsbuildPlugin({
                  target: 'es2015',
+                 css: true  // Apply minification to CSS assets
              })
          ]
      },

      module: {
          rules: [
              {
                  test: /\.css$/i,
                  use: [
                      MiniCssExtractPlugin.loader,
                      'css-loader'
                  ]
              }
          ],
      },

      plugins: [
          new MiniCssExtractPlugin()
      ]
  }

CSS in JS

If your CSS is not emitted as a .css file, but rather injected with JavaScript using something like style-loader, you can use the loader for minification.

In webpack.config.js:

  module.exports = {
      // ...,

      module: {
          rules: [
              {
                  test: /\.css$/i,
                  use: [
                      'style-loader',
                      'css-loader',
+                     {
+                         loader: 'esbuild-loader',
+                         options: {
+                             minify: true,
+                         },
+                     },
                  ],
              },
          ],
      },
  }

Bring your own esbuild (Advanced)

esbuild-loader comes with a version of esbuild it has been tested to work with. However, esbuild has a frequent release cadence, and while we try to keep up with the important releases, it can get outdated.

To work around this, you can use the implementation option in the loader or the plugin to pass in your own version of esbuild (eg. a newer one).

[!WARNING]
⚠esbuild is not stable yet and can have dramatic differences across releases. Using a different version of esbuild is not guaranteed to work.

+ const esbuild = require('esbuild')

  module.exports = {
      // ...,

      module: {
          rules: [
              {
                  test: ...,
                  loader: 'esbuild-loader',
                  options: {
                      // ...,
+                     implementation: esbuild,
                  },
              },
          ],
      },
  }

Setup examples

If you'd like to see working Webpack builds that use esbuild-loader for basic JS, React, TypeScript, Next.js, etc. check out the examples repo:

→ esbuild-loader examples

⚙️ Options

Loader

The loader supports all Transform options from esbuild.

Note:

  • Source-maps are automatically configured for you via devtool. sourcemap/sourcefile options are ignored.
  • The root tsconfig.json is automatically detected for you. You don't need to pass in tsconfigRaw unless it's in a different path.

Here are some common configurations and custom options:

tsconfig

Type: string

Pass in the file path to a custom tsconfig file. If the file name is tsconfig.json, it will automatically detect it.

target

Type: string | Array<string>

Default: 'es2015'

The target environment (e.g. es2016, chrome80, esnext).

Read more about it in the esbuild docs.

loader

Type: 'js' | 'jsx' | 'ts' | 'tsx' | 'css' | 'json' | 'text' | 'base64' | 'file' | 'dataurl' | 'binary' | 'default'

Default: 'default'

The loader to use to handle the file. See the type for possible values.

By default, it automatically detects the loader based on the file extension.

Read more about it in the esbuild docs.

jsxFactory

Type: string

Default: React.createElement

Customize the JSX factory function name to use.

Read more about it in the esbuild docs.

jsxFragment

Type: string

Default: React.Fragment

Customize the JSX fragment function name to use.

Read more about it in the esbuild docs.

implementation

Type: { transform: Function }

Custom esbuild-loader option.

Use it to pass in a different esbuild version.

EsbuildPlugin

The loader supports all Transform options from esbuild.

target

Type: string | Array<string>

Default: 'esnext'

Target environment (e.g. 'es2016', ['chrome80', 'esnext'])

Read more about it in the esbuild docs.

Here are some common configurations and custom options:

format

Type: 'iife' | 'cjs' | 'esm'

Default:

  • iife if both of these conditions are met:
    • Webpack's target is set to web
    • esbuild's target is not esnext
  • undefined (no format conversion) otherwise

The default is iife when esbuild is configured to support a low target, because esbuild injects helper functions at the top of the code. On the web, having functions declared at the top of a script can pollute the global scope. In some cases, this can lead to a variable collision error. By setting format: 'iife', esbuild wraps the helper functions in an IIFE to prevent them from polluting the global.

Read more about it in the esbuild docs.

minify

Type: boolean

Default: true

Enable JS minification. Enables all minify* flags below.

To have nuanced control over minification, disable this and enable the specific minification you want below.

Read more about it in the [esbuild

项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

稿定AI

稿定设计 是一个多功能的在线设计和创意平台,提供广泛的设计工具和资源,以满足不同用户的需求。从专业的图形设计师到普通用户,无论是进行图片处理、智能抠图、H5页面制作还是视频剪辑,稿定设计都能提供简单、高效的解决方案。该平台以其用户友好的界面和强大的功能集合,帮助用户轻松实现创意设计。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号