Initial commit: Bootstrap + Vite + Luxon project

parents
node_modules/
dist/
*.log
.DS_Store
*.tmp
build/
.cache/
.env
# Интеграция Bootstrap 5 в приложение с Luxon. Этап 3
**Выполнила:** Трофимцова Екатерина, ИВТ-1 (пг 2)
## 1. Цель работы
Интеграция Bootstrap 5 в приложение с использованием сборщика Vite, минимизация размера бандла за счет импорта тольео необходимых компонентов Bootstrap.
## 2. Команды для сборки
```bash
# Установка зависимостей
npm install bootstrap luxon
# Сборка проекта
npm run build
# Запускает проект на локальном сервере (http://localhost:4173/)
npm start
```
## 3. Интерфейс
![alt text](image-2.png)
![alt text](image-3.png)
Приложение состоит из кнопки по центру экрана, при нажатии на которую открывается модальное окно с текущим временем в формате "дд.мм.гг чч:мм:сс".
### Реализованный функционал:
- Сетка Bootstrap (container, row, col-*)
- Кнопка "Показать время"
- Модальное окно с отображением времени
- Обновление времени в реальном времени с помощью Luxon
- Адаптивный дизайн
- Интерактивность (открытие/закрытие модального окна)
## 4. Размеры бандла
### Со всеми компонентами Bootstrap:
`styles-full.scss`:
```scss
// Импортируем весь Bootstrap
@import "bootstrap";
```
![alt text](image.png)
383.05 kB
### Только с необходимыми компонентами Bootstrap:
`styles-minimal.scss`:
```scss
// Импортируем только необходимые компоненты Bootstrap
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/variables-dark";
@import "bootstrap/scss/maps";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/root";
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type"; // .fs-5
@import "bootstrap/scss/grid"; // .container, .row, .col-*
@import "bootstrap/scss/buttons"; // .btn, .btn-*
@import "bootstrap/scss/modal"; // .modal, .modal-*
@import "bootstrap/scss/close"; // .btn-close
@import "bootstrap/scss/utilities"; // .text-center
```
![alt text](image-1.png)
197.93 kB
## 5. Дополнительное задание: использование обфускатора
**Попробуйте, используя расширение для vite, выполнить минимизацию/обфускацию кода javascript, html, чтобы он стал меньше по размеру и зафиксируйте разницу с предыдущей сборкой, где код не минимизировался/обфусцировался.**
Был использован обфускатор `vite-plugin-bundle-obfuscator` и html-обфускатор `createHtmlPlugin` из библиотеки `vite-plugin-html`. Плагины были импортированы в `vite.config.js`, а также настроены их базовые конфинурации.
```js
const allObfuscatorConfig = {
excludes: [],
enable: true,
log: true,
autoExcludeNodeModules: true,
// autoExcludeNodeModules: { enable: true, manualChunks: ['vue'] }
threadPool: true,
// threadPool: { enable: true, size: 4 }
options: {
compact: true,
controlFlowFlattening: true,
controlFlowFlatteningThreshold: 1,
deadCodeInjection: false,
debugProtection: false,
debugProtectionInterval: 0,
disableConsoleOutput: false,
identifierNamesGenerator: 'hexadecimal',
log: false,
numbersToExpressions: false,
renameGlobals: false,
selfDefending: true,
simplify: true,
splitStrings: false,
ignoreImports: true,
stringArray: true,
stringArrayCallsTransform: true,
stringArrayCallsTransformThreshold: 0.5,
stringArrayEncoding: [],
stringArrayIndexShift: true,
stringArrayRotate: true,
stringArrayShuffle: true,
stringArrayWrappersCount: 1,
stringArrayWrappersChainedCalls: true,
stringArrayWrappersParametersMaxCount: 2,
stringArrayWrappersType: 'variable',
stringArrayThreshold: 0.75,
unicodeEscapeSequence: false,
}
};
...
plugins: [
vitePluginBundleObfuscator(allObfuscatorConfig),
createHtmlPlugin({
minify: true, // Включает минификацию HTML
})
]
...
```
Размеры бандла после обфускации бандла с импортом только необходимых компонент Bootstrap:
![alt text](image-2.png)
159.21 kB
## 6. Выводы
| С полным Bootstrap | Только с необходимыми компонентами Bootstrap | После обфускации|
|:--------------------:|:-------------:|:-----------------:|
| 383.05 kB | 197.93 kB | 159.21 kB |
| Уменьшение: | на 185.12 kB | еще на 38.72 kB |
| | на 48.3% | еще на 19.6% |
| Всего: | | на 58.4% |
Использование выборочного импорта Bootstrap уменьшило размер бандла практически вдвое (на 48.3%), что демонстрирует эффективность импорта только необходимых компонентов. Обфускация дала дополнительное уменьшение на 19.6%, что является значимым улучшением поверх уже оптимизированной версии. Комбинированный подход позволил уменьшить размер бандла на 58.4%, что составляет **сокращение более чем вдвое от исходного размера**.
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "bootstrap-vite",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "vite",
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"devDependencies": {
"sass": "^1.94.2",
"vite": "^7.2.2",
"vite-plugin-bundle-obfuscator": "^1.8.0",
"vite-plugin-html": "^3.2.2"
},
"dependencies": {
"bootstrap": "^5.3.2",
"luxon": "^3.7.2"
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Трофимцова Екатерина, ИВТ-1, bootstrap-vite</title>
<!-- <link rel="stylesheet" href="./scss/styles-full.scss"> -->
<link rel="stylesheet" href="./scss/styles-minimal.scss">
</head>
<body>
<div class="container text-center">
<div class="row">
<div class="col-2"></div>
<div class="col-8">
<button type="button" class="btn btn-danger btn-lg" data-bs-toggle="modal" data-bs-target="#exampleModal"
style=" width: 100%; height: 100%;
box-sizing: border-box;">
Показать время
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Трофимцова Екатерина, ИВТ-1</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<h1 id="hh"></h1>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-2">
</div>
</div>
</div>
<script type="module">
import * as bootstrap from 'bootstrap';
window.bootstrap = bootstrap;
</script>
<script type="module" src="/js/index.js"></script>
</body>
</html>
import { DateTime } from 'luxon';
setInterval(() => {
hh.textContent = DateTime
.local()
.setLocale('ru')
.toFormat('dd.LL.y HH:mm:ss');
}, 1000);
\ No newline at end of file
// Импортируем весь Bootstrap
@import "bootstrap";
\ No newline at end of file
// Импортируем только необходимые компоненты Bootstrap
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/variables-dark";
@import "bootstrap/scss/maps";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/root";
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type"; // .fs-5
@import "bootstrap/scss/grid"; // .container, .row, .col-*
@import "bootstrap/scss/buttons"; // .btn, .btn-*
@import "bootstrap/scss/modal"; // .modal, .modal-*
@import "bootstrap/scss/close"; // .btn-close
@import "bootstrap/scss/utilities"; // .text-center
\ No newline at end of file
import { resolve } from 'path';
import vitePluginBundleObfuscator from 'vite-plugin-bundle-obfuscator';
import { createHtmlPlugin } from 'vite-plugin-html';
const allObfuscatorConfig = {
excludes: [],
enable: true,
log: true,
autoExcludeNodeModules: true,
// autoExcludeNodeModules: { enable: true, manualChunks: ['vue'] }
threadPool: true,
// threadPool: { enable: true, size: 4 }
options: {
compact: true,
controlFlowFlattening: true,
controlFlowFlatteningThreshold: 1,
deadCodeInjection: false,
debugProtection: false,
debugProtectionInterval: 0,
disableConsoleOutput: false,
identifierNamesGenerator: 'hexadecimal',
log: false,
numbersToExpressions: false,
renameGlobals: false,
selfDefending: true,
simplify: true,
splitStrings: false,
ignoreImports: true,
stringArray: true,
stringArrayCallsTransform: true,
stringArrayCallsTransformThreshold: 0.5,
stringArrayEncoding: [],
stringArrayIndexShift: true,
stringArrayRotate: true,
stringArrayShuffle: true,
stringArrayWrappersCount: 1,
stringArrayWrappersChainedCalls: true,
stringArrayWrappersParametersMaxCount: 2,
stringArrayWrappersType: 'variable',
stringArrayThreshold: 0.75,
unicodeEscapeSequence: false,
}
};
export default {
root: resolve(__dirname, 'src'),
build: {
outDir: '../dist'
},
server: {
port: 8080
},
// Optional: Silence Sass deprecation warnings. See note below.
css: {
preprocessorOptions: {
scss: {
silenceDeprecations: [
'import',
'mixed-decls',
'color-functions',
'global-builtin',
],
},
},
},
plugins: [
vitePluginBundleObfuscator(allObfuscatorConfig),
createHtmlPlugin({
minify: true, // Включает минификацию HTML
})
]
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment