misc/class
lib/jquery_pnotify, lib/moment, lib/lodash, misc/notification, site/engine, misc/social
if( $.browser.msie && $.browser.version <= 8 ) include('lib/respond'); $._social.__cfg = {"init":[{"service":"basic"},{"fb_app_id":"1997094873850041","service":"fb"},{"vk_app_id":"2978320","service":"vk"},{"service":"twi"}],"like":[{"service":"fb"},{"service":"vk"},{"via":"","channel":"","hash_tag":"","service":"twi"}]}; window._SiteEngine = new classes.SiteEngine( { user_id: 0, controller: 'content_tape', action: 'tag', content_css_version: '1459538664', social_enabled: 0} );

Faiwer

Блог web-программиста

Поиск по метке: JavaScript

Babel to EsBuild migration for Webpack

9 февраля 2025

Recently I had some time to take a look at the performance of my pet project. One thing bothered me: the project is relatively small, but the bundle size was too big: 780 KiB. Whereas the project had only a few dependencies: react (~10 KiB), react-router (~70 KiB), react-dom (~90 KiB), dayjs (~3 KiB), lodash (~70 KiB). The bundle should not be that big for so few dependencies.

So I ran webpack-dev-analyzer and found a weird thing: the sum of the libs is 3 times smaller than the final bundle size. Then I decided to take a look at @statoscope/webpack-plugin. It was a good tool but it gave me the same result. The bundle has way too much trash. 

Ok. Probably it's just webpack wrappers over 300+ small modules. So I asked Perplexity - what can I do with it? Turned out all the proper options were already activated. So, I made a decision - it's time to try esbuild. It made a huge impact on my work project, so I knew it could work out. 

I knew that esbuild didn't support a lot of stuff that babel supports. So I expected that it would take a day to migrate the codebase to esbuild. But surprisingly once I replaced babel-loader with esbuild-loader the build command worked out. The build didn't work but the bundle was assembled without any errors.

Did it help? Nope. Instead of 780 KiB, I got ~1 MiB. Luckily I found out that there's also EsbuildPlugin, which replaces TerserPlugin and works better. Added this line, it worked like a charm, and... Whoa! 280 KiB. That's huuuge.

So I figured out - it worked. Now I have to find a way to fix the app (spoiler: it didn't work at all). 

Implicit React imports

React 17+ supports the possibility of avoiding adding import React from 'react' to every TSX-file. esbuild supports it too, but somehow it didn't work out of the box. Solution:

  const esbuildLoader: RuleSetRule = {
    test: /\.(js|ts|tsx)$/,
    loader: 'esbuild-loader',
    exclude: /node_modules/,
    options: {
       target: 'es2020',
       minify: cfg.PROD,
+      // Support implicit React imports:
+      jsx: 'automatic',
+      jsxFactory: 'React.createElement',
+      jsxImportSource: 'react',
    } satisfies LoaderOptions,
  };

TSX-Control-Statements

I just removed the packages and all their <If/>s. I liked them though. There's a plugin for Vite that adds their support. But I still use Webpack and the plugin works via string replacements, not via AST. 

SourceMaps

To enable sourcemaps I had to disable EsbuildPlugin for development. Theoretically, it supports sourcemaps, but no matter what I did it didn't work. I even debugged the package itself. Didn't help. So I surrendered and enabled it only for the prod build.

TypeScript

EsBuild supports TypeScript syntax out of the box but it doesn't check types. So it builds extremely fast but I need to know my errors. Solution:

  webpackConfig.plugins!.push(
    new ForkTsCheckerWebpackPlugin({
      typescript: {
        configFile: cfg.paths.TS_CONFIG,
      },
    })
  );

How does it work? The build and the type-checking processes are run in parallel. The 2nd doesn't linger the 1st. You still can see the errors in the browser (and CLI) console. And visually too. Nice.

ES-Lint

For some reason, it stopped working. The solution was pretty simple:

  webpackConfig.plugins!.push(
    new ESLintPlugin({
      extensions: ['ts', 'tsx'],

Final results

  • File sizes
    • Before: 641 KiB + 234 KiB + 29.5 KiB (css) = 904.5 KiB
    • After: 221 KiB + 55 KiB + 8.1 KiB (o_O, css) = 284.1 KiB
    • After minifyIdentifiers: true (scary thing) & minifyWhitespace: true:  138 KiB + 44.2 KiB + 8.1 KiB = 190.1 KiB
  • DOMContentLoaded:
    • Before: 737ms
    • After: 231ms
    • After-2: 131ms
  • Build time: esbuild was ~3x faster

Afterthought

Taking a deeper look I found:

  • The main issue wasn't in babel. The main issue was that I used inline-source-map for prod. I didn't want to do it. Just a mistake. And both bundle analyzers didn't notice that. Even when I manually looked at the file I barely found it (the horisontal scroll was too big). Fixing this issue dropped the file size 3x times even with babel.
  • esbuild has a better wrapper logic for a ton of tiny files than babel does. 
  • Whitespace minification is quite important. GZip doesn't eliminate the difference. 
  • Name mangling is a beast. But be careful, it can easily break your app in runtime. 

How to migrate Javascript webpack configuration to Typescript

25 марта 2023

It turned out that the newest versions (at least 5+) of webpack support Typescript out of the box. So the algorithm is next:

  • Create tsconfig.json at the root level. Content:
    {
      "compilerOptions": {
        "module": "CommonJS",
        "target": "ES5",
        "esModuleInterop": true,
        "checkJs": false,
        "strict": true,
      }
    }
    
  • Rename all *.js files to *.ts
  • Type all of them:
    • no more ugly require, use import.
    • webpack package has typings out of the box.
      • You may find these types useful: ConfigurationRuleSetRule
      • To enable devServer write this: 
        interface Configuration extends WebpackConfiguration {
          devServer?: WebpackDevServerConfiguration;
        }
        
    • Some of the popular plugins have types too.
    • Some of them don't have types at all:
      • Create a *.d.ts file
      • Put there something like this:
        declare module 'postcss-assets' {
          export default function postcssAssets(opts: {
            basePath: string;
            relative: boolean;
          }): unknown;
        }
        
  • Make sure your webpack.config.ts file is placed at the root level. I mean exactly at the same spot where node_modules is. Otherwise, you won't be able to build it. No compilerOptions helped me. 
  • Run webpack. It should work.

Multilayout Keybinds in a Browser

9 февраля 2022

Imagine that you want to add support of some keybinds in your web application. Let it be Ctrl+L for liking\unliking something. What kind of issues can you face in such a scenario?

CMD or Ctrl?

At first look at Ctrl. Probably on MacOS you'd like to replace it with CMD.  You can check it by event.metaKey.

Extra modificators

Probably you wouldn't like to consider Ctrl+Alt+S as Ctrl+S. So don't forget to handle this case.

Different layouts

Not every language that uses the Latin alphabet has the L button at the same position as in a typical English keyboard layout. You need to decide what is more important to you ― a real key position on a keyboard or a letter upon of it. I'd guess that the 2nd case is preferable for most applications. 

To get a real key position you can use which, code, codeKey properties. To get a letter on the key use key property.

Different alphabets

What's about Greek or Russian alphabets? Or any other possible alphabets? Or not even alphabets? There're different strategies. And one of them is to use a key from a typical English keyboard layout. So it leads us again to code and codeKey properties.

Example

const getEventKeyBind = event => {
  const keybind = [];

  if (event.metaKey) keybind.push('cmd');
  if (event.ctrlKey) keybind.push('ctrl');
  if (event.shiftKey) keybind.push('shift');
  if (event.altKey) keybind.push('alt');

  if (event.key === ' ') keybind.push('space');
  else {
    const key = event.key.toLowerCase();

    if (key.length !== 1 || key.match(/^[a-z]$/)) {
      // latin key or a special key
      keybind.push(key);
    } else {
      // extra-latin or non-latin key
      const [, enSymbol] = event.code.match(/^Key(\w)$/) || [];
      keybind.push(enSymbol ? enSymbol.toLowerCase() : key);
    }
  }

  return keybind.join('+');
};

Отладка NodeJS приложений при помощи ndb

3 августа 2018

Пост-заметка об ndb. Всем кто пишет для nodejs периодически приходится отлаживать своё приложение. Да даже тем, кто использует mocha или webpack бывает нет-нет да удобнее отладить по-человечески проблему, нежели тыкать повсюду console.log-и. NodeJS издавна предоставляет нам для этого браузерный инструмент.

Работает оно так:

  • мы запускаем наше приложение из консоли с нужным флагом
  • NodeJS в консоли нам сообщает ссылку с нужным портом
  • Которую мы открываем в браузере и видим перед собой копию chrome-dev-tools-ов.

Если надо перезагрузить приложение ― повторяем всё с нуля. С одной стороны сами инструменты весьма удобные. С другой стороны вся эта мышиная возня с портами и перезапусками очень неудобна.

И тут на помощь к нам приходит ndb. Просто перед командой запуска приложения добавляем ndb. Dev-tools-ы открываются прямо в своём отдельном окне. Перезагрузить приложение можно нажав ctrl+R. Все breakpoint-ы и прочая муть при этом сохраняется. 

Выглядит это всё примерно так:

Webpack и SCSS импорты в купе с module-resolver

3 августа 2018

С приходоим ES7 в JS пришли import-ы и export-ы. Жить стало веселее, и... сложнее. Появилось много заморочек и вообще новых проблем. Одна из таких проблем выглядит так: `import some from ../../../../../some`. Знакомая ситуация?

Обычно её в случае webpack-а решают при помощи модуля module-resolver. Он позволяет в .babelrc (или где вы держите конфигурацию) указывать регулярные выражения для автозамены, а также добавляет поддержку root-записей. Скажем с ним можно указать `import actions from '@actions/header', где `@actions` будет алиасом к какому-нибудь пути в вашем проекте. 

Дальше встаёт вопрос инструментов. А как на это должен реагировать редактор? Как он узнает, что теперь пути в import-ах устроены хитрее. Что делать с линтингом? К счастью, для eslint есть такой плагин:  eslint-plugin-import. С редакторами ситуация может быть сложнее.

Хорошо, а что делать с SCSS\Sass? Нормальных рабочих решений с наскоку мне найти не удалось. Но как оказалось, всё можно решить относительно просто. В настройках webpack для sass-loader-а можно указать настройки. Они будут переданы как есть в пакет node-sass. А вот он, оказывается, достаточно гибкий. Если там указать метод importer, то можно навязать свою логику обработки @import-ов. Пример:

{
	loader: 'sass-loader',
	options:
	{
		sourceMap: true,
		url: false,
		importer: url => (
		{
			file: url
				.replace(...)
				.replace(...)
				.replace(...),
		}),
	},
}

Либо даже выцепить ваши настройки прямо из настроек в .babelrc.