Skip to content

refact: JS size optimization #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions .dev_to/case-study-template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Case-study оптимизации

## Актуальная проблема
В проекте `dev.to` есть определенная проблема. Анализ показывает, что на всех страницах загружается файл `vendor.js`.

Этот файл содержит библиотеку moment.js, печально известную своим большим размером.

У нас уже была программа на `ruby`, которая умела делать нужную обработку.

## Формирование метрики
В качестве метрики берем объём `js` на главной странице.

В файле `homeBudget.json` устанавливаем бюджет в 460000 байт.

## Анализ
С помощью `sitespeed.io` убеждаемся, что бюджет пока не соблюдается:
`docker run --privileged --rm -v "$(pwd)":/sitespeed.io sitespeedio/sitespeed.io http://host.docker.internal:3000/ -n 1 --budget.configPath homeBudget.json`

![sitespeed_before.png](/public/reports/sitespeed_before.png)

С помощью `webpack-bundle-analyzer` убедился, что `moment.js` входит в сборку `vendor`:

![bundle_analyze_before.png](/public/reports/bundle_analyze_before.png)

Закомментировал содержимое файла `proCharts.js`. `web-bundle-analyzer` показал что `moment` пропал из `vendor`:

![bundle_analyze_after.png](/public/reports/bundle_analyze_after.png)


## Оптимизация
В первую очередь я раскомментировал содержимое файла `proCharts.js`.

Проанализировав отчеты и код проекта я выяснил что `proCharts.js` использует `chart.js`, которая, в свою очередь, внутри использует `moment.js`.
Поэтому `moment` попадает в `vendor` вместе с `chart.js`, и они оказываются связанными.

В качестве оптимизации отредактировал `CommonsChunkPlugin` в `environment.js` путём исключения `chart.js` и `moment.js` из `vendor` сборки.
Этим мы можем гарантировать что теперь они будут подключаться только там, где непосредственно используются.
```
!module.context.includes('chart.js') && !module.context.includes('moment')
```
С помощью `web-bundle-analyzer` убедился, что это сработало:

![bundle_analyze_after_optimization.png](/public/reports/bundle_analyze_after_optimization.png)

Однако `sitespeed.io` показал что бюджет еще не выполнен:
![sitespeed_after.png](/public/reports/sitespeed_after.png)

В `webpack-bundle-analyzer` заметил, что в `vendor` остались 2 зависимости `chartjs-color` и `chartjs-color-string`. Поэтому их также исключил из `vendor`.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


Теперь бюджет выполняется:
![sitespeed_finish.png](/public/reports/sitespeed_finish.png)

## CI
Защитил оптимизацию, настроив CI Github Actions:
https://github.com/alexrails/rails-optimization-task6/actions/runs/13750720227
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

7 changes: 7 additions & 0 deletions .dev_to/sitespeed/homeBudget.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"budget": {
"transferSize": {
"javascript": 460000
}
}
}
10 changes: 10 additions & 0 deletions .github/workflows/sitespeedio.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name: sitespeedio
on: [push]
jobs:
build:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше check_js_size или что-то такое

runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v4
- name: run sitespeed.io
run: docker run --privileged --rm -v "$(pwd):/sitespeed.io" sitespeedio/sitespeed.io https://03d1-2a0b-6204-12ef-c100-6424-8e72-d575-70d0.ngrok-free.app -n 1 --budget.configPath .dev_to/sitespeed/homeBudget.json
14 changes: 13 additions & 1 deletion config/webpack/environment.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ environment.plugins.append(
name: 'vendor',
minChunks: (module) => {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module.context.indexOf('node_modules') !== -1
return module.context && module.context.indexOf('node_modules') !== -1 &&
!/chart\.js|chartjs|color-name|color-convert/.test(module.context) &&
!module.context.includes('moment')
}
})
)
Expand All @@ -31,4 +33,14 @@ environment.plugins.append(
})
)

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
.BundleAnalyzerPlugin;
environment.plugins.append(
'BundleAnalyzer',
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: true,
}),
);

module.exports = environment
Binary file added public/reports/bundle_analyze_after.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/reports/bundle_analyze_before.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/reports/sitespeed_after.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/reports/sitespeed_before.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/reports/sitespeed_finish.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.