Webpack chunks что это

Еще один способ использования Webpack 4 и разделение кода

Ни для кого не секрет, что с выходом Webpack 4 стратегия разделения кода сильно поменялась. Тут даже лучше сказать, что она была заново придумана, т.к. старый подход просто перестал работать, а новый не понятно как использовать.

Для тех, кто все еще не в курсе, плагина webpack.optimize.CommonsChunkPlugin больше нет. Совсем. Вместо этого предлагается в конфиге писать следующее:

Это должно работать как магия. Т.е. теперь не мы говорим webpack’у что сделать общим чанком, а он сам все сделает, да еще может даже и лучше нас.

И наступит счастье. Шутка. На самом деле нет.

Базовые приготовления

Вот пример из документации:

Результатом сборки будут 3 файла: another.bundle.js, index.bundle.js, vendors

Теперь, для того, чтобы запустить наши веб приложения, мы, в одном случае, должны подключить vendors

index.bundle.js и index.bundle.js, а во втором vendors

index.bundle.js и another.bundle.js.

В чем проблема?

Проблема в имени vendors

index.bundle.js. Пока у нас меньше трех точек входа, ничего страшного не происходит. Здесь все кажется логичным — бандл содержит npm модули (они же vendors) и общие модули для index и another. На каждую из страниц мы подключаем 2 файла и не имеем проблем.

Однако если у нас три и более точки входа, то новых бандлов (они же чанки) может быть куда больше и мы уже не знаем ни их количества, ни имен. Все становится еще веселее, если мы еще и css извлекаем в отдельные файлы. И это проблема.

Как решить эту проблему?

После завершения работы webpack у нас нет никаких файлов, которые содержали бы в себе информацию о том, какие именно бандлы на той или иной странице надо подключать. И в какой последовательности.

Однако в output’е мы можем найти вот такие строки:

На самом деле это почти то, что нам надо. Т.е. webpack прекрасно знает какие бандлы нужны для каждой точки входа, но почему-то сам не хочет этой информацией с нами делиться.

Манифест нам здесь не помогает. Да, мы знаем что такой (vendors

index.bundle.js) бандл есть. Мы знаем где он лежит. Но кому он нужен не знаем. Т.е. манифест бесполезен.

Тогда я решил что раз webpack знает нужную информацию, то ее возможно получится достать с помощью плагинов. Готовых я не нашел и решил написать свой. И, только ради демонстрации этого плагина, я и пишу эту статью.

В файле webpack.config.(ts|js) добавим новый плагин:

и дождемся результата. Результатом будет файл entrypoints.json с вот таким содержанием:

Если используется extract-css, то кроме секции js будет еще и css.

Источник

Code Splitting

This guide extends the example provided in Getting Started. Please make sure you are at least familiar with the example provided there and the Output Management chapter.

Code splitting is one of the most compelling features of webpack. This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel. It can be used to achieve smaller bundles and control resource load prioritization which, if used correctly, can have a major impact on load time.

There are three general approaches to code splitting available:

Entry Points

This is by far the easiest and most intuitive way to split code. However, it is more manual and has some pitfalls we will go over. Let’s take a look at how we might split another module from the main bundle:

project

another-module.js

webpack.config.js

This will yield the following build result:

As mentioned there are some pitfalls to this approach:

Prevent Duplication

Entry dependencies

The dependOn option allows to share the modules between the chunks:

webpack.config.js

If we’re going to use multiple entry points on a single HTML page, optimization.runtimeChunk: ‘single’ is needed too, otherwise we could get into trouble described here.

webpack.config.js

And here’s the result of build:

Although using multiple entry points per page is allowed in webpack, it should be avoided when possible in favor of an entry point with multiple imports: entry: < page: ['./analytics', './app'] >. This results in a better optimization and consistent execution order when using async script tags.

SplitChunksPlugin

The SplitChunksPlugin allows us to extract common dependencies into an existing entry chunk or an entirely new chunk. Let’s use this to de-duplicate the lodash dependency from the previous example:

webpack.config.js

Here are some other useful plugins and loaders provided by the community for splitting code:

Dynamic Imports

warning

import() calls use promises internally. If you use import() with older browsers (e.g., IE 11), remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.

Before we start, let’s remove the extra entry and optimization.splitChunks from our configuration in the above example as they won’t be needed for this next demonstration:

webpack.config.js

We’ll also update our project to remove the now unused files:

project

src/index.js

Let’s run webpack to see lodash separated out to a separate bundle:

As import() returns a promise, it can be used with async functions. Here’s how it would simplify the code:

src/index.js

It is possible to provide a dynamic expression to import() when you might need to import specific module based on a computed variable later.

Prefetching/Preloading modules

Webpack 4.6.0+ adds support for prefetching and preloading.

Using these inline directives while declaring your imports allows webpack to output “Resource Hint” which tells the browser that for:

An example of this is having a HomePage component, which renders a LoginButton component which then on demand loads a LoginModal component after being clicked.

LoginButton.js

webpack will add the prefetch hint once the parent chunk has been loaded.

Preload directive has a bunch of differences compared to prefetch:

An example of this can be having a Component which always depends on a big library that should be in a separate chunk.

ChartComponent.js

Using webpackPreload incorrectly can actually hurt performance, so be careful when using it.

Bundle Analysis

Once you start splitting your code, it can be useful to analyze the output to check where modules have ended up. The official analyze tool is a good place to start. There are some other community-supported options out there as well:

Next Steps

See Lazy Loading for a more concrete example of how import() can be used in a real application and Caching to learn how to split code more effectively.

Источник

SplitChunksPlugin

Originally, chunks (and modules imported inside them) were connected by a parent-child relationship in the internal webpack graph. The CommonsChunkPlugin was used to avoid duplicated dependencies across them, but further optimizations were not possible.

Defaults

Out of the box SplitChunksPlugin should work well for most users.

By default it only affects on-demand chunks, because changing initial chunks would affect the script tags the HTML file should include to run the project.

Webpack will automatically split chunks based on these conditions:

When trying to fulfill the last two conditions, bigger chunks are preferred.

Configuration

Webpack provides a set of options for developers that want more control over this functionality.

warning

The default configuration was chosen to fit web performance best practices, but the optimal strategy for your project might differ. If you’re changing the configuration, you should measure the effect of your changes to ensure there’s a real benefit.

optimization.splitChunks

webpack.config.js

warning

When files paths are processed by webpack, they always contain / on Unix systems and \ on Windows. That’s why using [\\/] in .test fields is necessary to represent a path separator. / or \ in .test will cause issues when used cross-platform.

warning

Since webpack 5, passing an entry name to .test and using a name of an existing chunk for .name is no longer allowed.

splitChunks.automaticNameDelimiter

By default webpack will generate names using origin and name of the chunk (e.g. vendors

main.js ). This option lets you specify the delimiter to use for the generated names.

splitChunks.chunks

string = ‘async’ function (chunk)

Note that it is applied to the fallback cache group as well ( splitChunks.fallbackCacheGroup.chunks ).

webpack.config.js

Alternatively, you may provide a function for more control. The return value will indicate whether to include each chunk.

You can combine this configuration with the HtmlWebpackPlugin. It will inject all the generated vendor chunks for you.

splitChunks.maxAsyncRequests

Maximum number of parallel requests when on-demand loading.

splitChunks.maxInitialRequests

Maximum number of parallel requests at an entry point.

splitChunks.defaultSizeTypes

[string] = [‘javascript’, ‘unknown’]

Sets the size types which are used when a number is used for sizes.

splitChunks.minChunks

The minimum times must a module be shared among chunks before splitting.

splitChunks.hidePathInfo

Prevents exposing path info when creating names for parts splitted by maxSize.

splitChunks.minSize

Minimum size, in bytes, for a chunk to be generated.

splitChunks.minSizeReduction

Minimum size reduction to the main chunk (bundle), in bytes, needed for a chunk to be generated. Meaning if splitting into a chunk does not reduce the size of the main chunk (bundle) by the given amount of bytes, it won’t be split, even if it meets the splitChunks.minSize value.

Both splitChunks.minSizeReduction and splitChunks.minSize need to be fulfilled for a chunk to be generated.

splitChunks.enforceSizeThreshold

splitChunks.cacheGroups..enforceSizeThreshold

Size threshold at which splitting is enforced and other restrictions (minRemainingSize, maxAsyncRequests, maxInitialRequests) are ignored.

splitChunks.minRemainingSize

splitChunks.cacheGroups..minRemainingSize

splitChunks.minRemainingSize option was introduced in webpack 5 to avoid zero sized modules by ensuring that the minimum size of the chunk which remains after splitting is above a limit. Defaults to 0 in ‘development’ mode. For other cases splitChunks.minRemainingSize defaults to the value of splitChunks.minSize so it doesn’t need to be specified manually except for the rare cases where deep control is required.

warning

splitChunks.minRemainingSize only takes effect when a single chunk is remaining.

splitChunks.layer

splitChunks.cacheGroups..layer

RegExp string function

Assign modules to a cache group by module layer.

splitChunks.maxSize

When the chunk has a name already, each part will get a new name derived from that name. Depending on the value of optimization.splitChunks.hidePathInfo it will add a key derived from the first module name or a hash of it.

maxSize option is intended to be used with HTTP/2 and long term caching. It increases the request count for better caching. It could also be used to decrease the file size for faster rebuilding.

splitChunks.maxAsyncSize

The difference between maxAsyncSize and maxSize is that maxAsyncSize will only affect on-demand loading chunks.

splitChunks.maxInitialSize

The difference between maxInitialSize and maxSize is that maxInitialSize will only affect initial load chunks.

splitChunks.name

boolean = false function (module, chunks, cacheGroupKey) => string string

The name of the split chunk. Providing false will keep the same name of the chunks so it doesn’t change names unnecessarily. It is the recommended value for production builds.

Providing a string or a function allows you to use a custom name. Specifying either a string or a function that always returns the same string will merge all common modules and vendors into a single chunk. This might lead to bigger initial downloads and slow down page loads.

If you choose to specify a function, you may find the chunk.name and chunk.hash properties (where chunk is an element of the chunks array) particularly useful in choosing a name for your chunk.

If the splitChunks.name matches an entry point name, the entry point will be removed.

main.js

webpack.config.js

Running webpack with following splitChunks configuration would also output a chunk of the group common with next name: commons-main-lodash.js.e7519d2bb8777058fa27.js (hash given as an example of real world output).

warning

When assigning equal names to different split chunks, all vendor modules are placed into a single shared chunk, though it’s not recommend since it can result in more code downloaded.

splitChunks.usedExports

splitChunks.cacheGroups.usedExports

Figure out which exports are used by modules to mangle export names, omit unused exports and generate more efficient code. When it is true : analyse used exports for each runtime, when it is «global» : analyse exports globally for all runtimes combined).

splitChunks.cacheGroups

webpack.config.js

splitChunks.cacheGroups..priority

splitChunks.cacheGroups..reuseExistingChunk

If the current chunk contains modules already split out from the main bundle, it will be reused instead of a new one being generated. This can affect the resulting file name of the chunk.

webpack.config.js

splitChunks.cacheGroups..type

function RegExp string

Allows to assign modules to a cache group by module type.

webpack.config.js

splitChunks.cacheGroups.test

splitChunks.cacheGroups..test

function (module, < chunkGraph, moduleGraph >) => boolean RegExp string

Controls which modules are selected by this cache group. Omitting it selects all modules. It can match the absolute module resource path or chunk names. When a chunk name is matched, all modules in the chunk are selected.

Providing a function to .test :

webpack.config.js

In order to see what information is available in module and chunks objects, you can put debugger; statement in the callback. Then run your webpack build in debug mode to inspect the parameters in Chromium DevTools.

Providing a RegExp to .test :

webpack.config.js

splitChunks.cacheGroups..filename

string function (pathData, assetInfo) => string

Allows to override the filename when and only when it’s an initial chunk. All placeholders available in output.filename are also available here.

warning

webpack.config.js

webpack.config.js

webpack.config.js

splitChunks.cacheGroups..enforce

webpack.config.js

splitChunks.cacheGroups..idHint

Sets the hint for chunk id. It will be added to chunk’s filename.

webpack.config.js

Examples

Defaults: Example 1

What’s the reasoning behind this? react probably won’t change as often as your application code. By moving it into a separate chunk this chunk can be cached separately from your app code (assuming you are using chunkhash, records, Cache-Control or other long term cache approach).

Defaults: Example 2

Putting the content of helpers into each chunk will result into its code being downloaded twice. By using a separate chunk this will only happen once. We pay the cost of an additional request, which could be considered a tradeoff. That’s why there is a minimum size of 30kb.

Split Chunks: Example 1

Create a commons chunk, which includes all code shared between entry points.

webpack.config.js

warning

This configuration can enlarge your initial bundles, it is recommended to use dynamic imports when a module is not immediately needed.

Split Chunks: Example 2

Create a vendors chunk, which includes all code from node_modules in the whole application.

webpack.config.js

warning

This might result in a large chunk containing all external packages. It is recommended to only include your core frameworks and utilities and dynamically load the rest of the dependencies.

Split Chunks: Example 3

webpack.config.js

This will result in splitting react and react-dom into a separate chunk. If you’re not sure what packages have been included in a chunk you may refer to Bundle Analysis section for details.

Источник

Пособие по webpack

Webpack chunks что это. Смотреть фото Webpack chunks что это. Смотреть картинку Webpack chunks что это. Картинка про Webpack chunks что это. Фото Webpack chunks что это

Давайте сначала разберемся, зачем нужен вебпак (webpack), и какие проблемы он пытается решить, а потом научимся работать с ним. Webpack позволяет избавиться от bower и gulp/grunt в приложении, и заменить их одним инструментом. Вместо bower’а для установки и управления клиентскими зависимостями, можно использовать стандартный Node Package Manager (npm) для установки и управления всеми фронтэнд-зависимостями. Вебпак также может выполнять большинство задач grunt/gulp’а.

Bower это пакетный менеджер для клиентской части. Его можно использовать для поиска, установки, удаления компонентов на JavaScript, HTML и CSS. GruntJS это JavaScript-утилита командной строки, помогающая разработчикам автоматизировать повторяющиеся задачи. Можно считать его JavaScript-альтернативой Make или Ant. Он занимается задачами вроде минификации, компиляции, юнит-тестирования, линтинга и пр.

Допустим, мы пишем простую страницу профиля пользователя в веб-приложении. Там используется jQuery и библиотеки underscore. Один из способов — включить оба файла в HTML:

Это простой HTML с Бутстрапом. Мы подключили jQuery и underscore с помощью тега script.

Код будет исполнен при вызове скрипта. Если открыть страницу в браузере, то профиль будет выглядеть так.

Webpack chunks что это. Смотреть фото Webpack chunks что это. Смотреть картинку Webpack chunks что это. Картинка про Webpack chunks что это. Фото Webpack chunks что это

У этого кода две задачи:

Известно, что смешивать понятия — плохая практика, так что нужно написать отдельные модули, отвечающие за определенные задачи. В файле profile.js мы использовали анонимное замыкание для хранения всего кода. В JavaScript есть способы делать модули получше. Два популярных способа это CommonJS и AMD.

Если хотите узнать о модулях в JavaScript больше, то советую прочитать статью JavaScript Modules: A Beginner’s Guide.

Если загрузить index.html в браузере, то отобразится пустая страница. В консоли (в developer tools) можно обнаружить ошибку:

Проблема в том, что браузеры не понимают модульную систему вроде CommonJS. Нужно предоставить браузеру формат, который он ожидает.

Бандлеры модулей идут на помощь

Что такое вебпак?

webpack берет модули с зависимостями и генерирует статические ресурсы, которые представляют эти модули

Это определение теперь имеет смысл, когда понятна решаемая проблема. Вебпак берет набор ресурсов и трансформирует их в наборы (бандлы).

Webpack chunks что это. Смотреть фото Webpack chunks что это. Смотреть картинку Webpack chunks что это. Картинка про Webpack chunks что это. Фото Webpack chunks что это

Трансформацией ресурсов занимаются загрузчики, которые являются сердцем вебпака.

Вебпак в действии

Для установки вебпака нужен node. Можно скачать node с официального сайта.

Теперь можно установить вебпак глобально:

В дополнение, нужно установить вебпак как зависимость.

Давайте создадим бандл.

Теперь страница работает нормально.

Можно сделать так, чтобы вебпак следил за изменениями и генерировал бандл автоматически. Для этого нужно запустить его с таким флагом:

Теперь вебпак не будет завершаться сам. При изменении файлов будет генерироваться новый бандл. Нужно лишь перезагрузить страницу в браузере. Давайте изменим profile.js :

Вебпак сгенерирует source map для файла bundle.js. Source map связывает минимизированный и собранный в один файл код с исходным, несобранным кодом. Для тестирования можно добавить строчку debugger в profile.js

Перезагрузите страницу, и приложение остановится на этой строке.

Webpack chunks что это. Смотреть фото Webpack chunks что это. Смотреть картинку Webpack chunks что это. Картинка про Webpack chunks что это. Фото Webpack chunks что это

Добавление CSS

вебпак перезагрузит изменения, и мы увидим сообщение об ошибке в консоли:

Проблема в том, что вебпак не понимает CSS по умолчанию. Нужно установить пару загрузчиков для этого. Вот команда для установки необходимых загрузчиков:

Вебпак использует загрузчики для трансформации текста в нужный формат. Теперь нужно обновить require :

Запустите вебпак снова.

Конфигурация

Чтобы не указывать все опции в командной строке, можно создать конфигурационный файл webpack.config.js в корне приложения:

После изменений конфигурации нужно перезапускать вебпак.

Горячая перезагрузка

На сегодня все. Узнать больше о вебпаке можно из документации.

Источник

Webpack: руководство для начинающих

Webpack chunks что это. Смотреть фото Webpack chunks что это. Смотреть картинку Webpack chunks что это. Картинка про Webpack chunks что это. Фото Webpack chunks что это

Доброго времени суток, друзья!

Представляю вашему вниманию перевод статьи «Webpack: A gentle introduction» автора Tyler McGinnis.

Перед изучением новой технологии задайте себе два вопроса:

Зачем нужен вебпак?

Вебпак — это сборщик модулей. Он анализирует модули приложения, создает граф зависимостей, затем собирает модули в правильном порядке в один или более бандл (bundle), на который может ссылаться файл «index.html».

Какие проблемы решает вебпак?

Обычно, при создании приложения на JavaScript, код разделяется на несколько частей (модулей). Затем в файле «index.html» необходимо указать ссылку на каждый скрипт.

Это не только утомительно, но и подвержено ошибкам. Важно не только не забыть про какой-нибудь скрипт, но и расположить их в правильном порядке. Если загрузить скрипт, зависящий от React, до загрузки самого React, приложение сломается. Вебпак решает эти задачи. Не нужно беспокоиться о последовательном включении всех скриптов.

Как мы скоро узнаем, сбор модулей является лишь одним из аспектов работы вебпака. При необходимости можно заставить вебпак осуществить некоторые преобразования модулей перед их добавлением в бандл. Например, преобразование SASS/LESS в обычный CSS, или современного JavaScript в ES5 для старых браузеров.

Установка вебпака

webpack.config.js

Основной задачей вебпака является анализ модулей, их опциональное преобразование и интеллектуальное объединение в один или более бандл, поэтому вебпаку нужно знать три вещи:

Точка входа

Сколько бы модулей не содержало приложение, всегда имеется единственная точка входа. Этот модуль включает в себя остальные. Обычно, таким файлом является index.js. Это может выглядеть так:

Если мы сообщим вебпаку путь до этого файла, он использует его для создания графа зависимостей приложения. Для этого необходимо добавить свойство entry в настройки вебпака со значением пути к главному файлу:

Преобразования с помощью лоадеров (loaders)

После добавления точки входа, нужно сообщить вебпаку о преобразованиях, которые необходимо выполнить перед генерацией бандла. Для этого используются лоадеры.

По умолчанию при создании графика зависимостей на основе операторов import / require() вебпак способен обрабатывать только JavaScript и JSON-файлы.

Едва ли в своем приложении вы решитесь ограничиться JS и JSON-файлами, скорее всего, вам также потребуются стили, SVG, изображения и т.д. Вот где нужны лоадеры. Основной задачей лоадеров, как следует из их названия, является предоставление вебпаку возможности работать не только с JS и JSON-файлами.

Первым делом нужно установить лоадер. Поскольку мы хотим загружать SVG, с помощью npm устанавливаем svg-loader.

Далее добавляем его в настройки вебпака. Все лоадеры включаются в массив объектов module.rules :

Существуют лоадеры почти для любого типа файлов.

Точка выхода

Теперь вебпак знает о точке входа и лоадерах. Следующим шагом является указание директории для бандла. Для этого нужно добавить свойство output в настройки вебпака.

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

Плагины (plugins)

Мы рассмотрели, как использовать лоадеры для обработки отдельных файлов перед или в процессе генерации бандла. В отличие от лоадеров, плагины позволяют выполнять задачи после сборки бандла. Эти задачи могут касаться как самого бандла, так и другого кода. Вы можете думать о плагинах как о более мощных, менее ограниченных лоадерах.

Давайте рассмотрим пример.

HtmlWebpackPlugin

HtmlWebpackPlugin создает index.html в директории с бандлом и автоматически добавляет в него ссылку на бандл.

Как нам использовать этот плагин? Как обычно, сначала его нужно установить.

EnvironmentPlugin

HtmlWebpackPlugin и EnvironmentPlugin — это лишь небольшая часть системы плагинов вебпака.

Режим (mode)

Существуют специальные плагины для решения указанных задачи, но есть более легкий способ. В настройках вебпака можно установить mode в значение development или production в зависимости от среды разработки.

Запуск вебпака

На данный момент мы знаем, как работает вебпак и как его настраивать, осталось его запустить.

Режимы разработки и продакшна

В целом, мы закончили с вебпаком. Напоследок давайте рассмотрим, как переключаться между режимами.

При сборке для продакшна, мы хотим все оптимизировать, насколько это возможно. В случае с режимом разработки верно обратное.

npm run build будет собирать продакшн-бандл.

npm run start будет запускать сервер для разработки и следить за изменениями файлов.

Сервер для разработки

Теперь у нас имеется две команды: одна для запуска сервера для разработки, другая для сборки готового бандла.

Надеюсь, статья была вам полезной. Благодарю за внимание.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *