How to use webpack

How to use webpack

Production

In this guide, we’ll dive into some of the best practices and utilities for building a production site or application.

This walkthrough stems from Tree Shaking and Development. Please ensure you are familiar with the concepts/setup introduced in those guides before continuing on.

Setup

The goals of development and production builds differ greatly. In development, we want strong source mapping and a localhost server with live reloading or hot module replacement. In production, our goals shift to a focus on minified bundles, lighter weight source maps, and optimized assets to improve load time. With this logical separation at hand, we typically recommend writing separate webpack configurations for each environment.

Let’s start by installing webpack-merge and splitting out the bits we’ve already worked on in previous guides:

project

webpack.common.js

webpack.dev.js

webpack.prod.js

NPM Scripts

package.json

Feel free to run those scripts and see how the output changes as we continue adding to our production configuration.

Specify the Mode

Many libraries will key off the process.env.NODE_ENV variable to determine what should be included in the library. For example, when process.env.NODE_ENV is not set to ‘production’ some libraries may add additional logging and testing to make debugging easier. However, with process.env.NODE_ENV set to ‘production’ they might drop or add significant portions of code to optimize how things run for your actual users. Since webpack v4, specifying mode automatically configures DefinePlugin for you:

webpack.prod.js

src/index.js

Minification

Note that while the TerserPlugin is a great place to start for minification and being used by default, there are other options out there:

Source Mapping

We encourage you to have source maps enabled in production, as they are useful for debugging as well as running benchmark tests. That said, you should choose one with a fairly quick build speed that’s recommended for production use (see devtool ). For this guide, we’ll use the source-map option in the production as opposed to the inline-source-map we used in the development:

webpack.prod.js

Avoid inline-*** and eval-*** use in production as they can increase bundle size and reduce the overall performance.

Minimize CSS

It is crucial to minimize your CSS for production. Please see the Minimizing for Production section.

CLI Alternatives

While these shorthand methods are useful, we recommend setting these options in a webpack configuration file for more configurability.

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

How to use webpack. Смотреть фото How to use webpack. Смотреть картинку How to use webpack. Картинка про How to use webpack. Фото How to use webpack

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

Представляю вашему вниманию перевод статьи «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 будет запускать сервер для разработки и следить за изменениями файлов.

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

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

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

Asset Management

If you’ve been following the guides from the start, you will now have a small project that shows «Hello webpack». Now let’s try to incorporate some other assets, like images, to see how they can be handled.

Prior to webpack, front-end developers would use tools like grunt and gulp to process these assets and move them from their /src folder into their /dist or /build directory. The same idea was used for JavaScript modules, but tools like webpack will dynamically bundle all dependencies (creating what’s known as a dependency graph). This is great because every module now explicitly states its dependencies and we’ll avoid bundling modules that aren’t in use.

One of the coolest webpack features is that you can also include any other type of file, besides JavaScript, for which there is a loader or built-in Asset Modules support. This means that the same benefits listed above for JavaScript (e.g. explicit dependencies) can be applied to everything used in building a website or web app. Let’s start with CSS, as you may already be familiar with that setup.

Setup

Let’s make a minor change to our project before we get started:

dist/index.html

webpack.config.js

Loading CSS

In order to import a CSS file from within a JavaScript module, you need to install and add the style-loader and css-loader to your module configuration:

webpack.config.js

Module loaders can be chained. Each loader in the chain applies transformations to the processed resource. A chain is executed in reverse order. The first loader passes its result (resource with applied transformations) to the next one, and so forth. Finally, webpack expects JavaScript to be returned by the last loader in the chain.

This enables you to import ‘./style.css’ into the file that depends on that styling. Now, when that module is run, a tag with the stringified css will be inserted into the of your html file.

Let’s try it out by adding a new style.css file to our project and import it in our index.js :

project

src/style.css

src/index.js

Now run your build command:

Note that you can, and in most cases should, minimize css for better load times in production. On top of that, loaders exist for pretty much any flavor of CSS you can think of – postcss, sass, and less to name a few.

Loading Images

So now we’re pulling in our CSS, but what about our images like backgrounds and icons? As of webpack 5, using the built-in Asset Modules we can easily incorporate those in our system as well:

webpack.config.js

Let’s add an image to our project and see how this works, you can use any image you like:

project

src/index.js

src/style.css

Let’s create a new build and open up the index.html file again:

Loading Fonts

So what about other assets like fonts? The Asset Modules will take any file you load through them and output it to your build directory. This means we can use them for any kind of file, including fonts. Let’s update our webpack.config.js to handle font files:

webpack.config.js

Add some font files to your project:

project

With the loader configured and fonts in place, you can incorporate them via an @font-face declaration. The local url(. ) directive will be picked up by webpack, as it was with the image:

src/style.css

Now run a new build and let’s see if webpack handled our fonts:

Open up dist/index.html again and see if our Hello webpack text has changed to the new font. If all is well, you should see the changes.

Loading Data

Another useful asset that can be loaded is data, like JSON files, CSVs, TSVs, and XML. Support for JSON is actually built-in, similar to NodeJS, meaning import Data from ‘./data.json’ will work by default. To import CSVs, TSVs, and XML you could use the csv-loader and xml-loader. Let’s handle loading all three:

webpack.config.js

Add some data files to your project:

project

src/data.xml

src/data.csv

Now you can import any one of those four types of data (JSON, CSV, TSV, XML) and the Data variable you import, will contain parsed JSON for consumption:

src/index.js

This can be especially helpful when implementing some sort of data visualization using a tool like d3. Instead of making an ajax request and parsing the data at runtime you can load it into your module during the build process so that the parsed data is ready to go as soon as the module hits the browser.

warning

Only the default export of JSON modules can be used without warning.

Customize parser of JSON modules

src/data.toml

src/data.yaml

src/data.json5

And configure them in your webpack configuration:

webpack.config.js

src/index.js

Global Assets

The coolest part of everything mentioned above, is that loading assets this way allows you to group modules and assets in a more intuitive way. Instead of relying on a global /assets directory that contains everything, you can group assets with the code that uses them. For example, a structure like this can be useful:

This setup makes your code a lot more portable as everything that is closely coupled now lives together. Let’s say you want to use /my-component in another project, copy or move it into the /components directory over there. As long as you’ve installed any external dependencies and your configuration has the same loaders defined, you should be good to go.

Wrapping up

For the next guides we won’t be using all the different assets we’ve used in this guide, so let’s do some cleanup so we’re prepared for the next piece of the guides Output Management:

project

webpack.config.js

src/index.js

And remove those dependencies we added before:

Command Line Interface

Read the installation guide if you don’t already have webpack and CLI installed.

warning

If you want to run webpack using npx please make sure you have webpack-cli installed.

Commands

webpack-cli offers a variety of commands to make working with webpack easier. By default webpack ships with

Build

Run webpack (default command, can be omitted).

example

Used to initialize a new webpack project.

example

Generation Path

Options

Name of template to generate.

To generate a project without questions. When enabled, the default answer for each question will be used.

Loader

Scaffold a loader.

example

Output Path

Options

Type of template.

Plugin

Scaffold a plugin.

example

Output Path

Options

Type of template.

Outputs information about your system.

example

Options for info

Adds additional packages to the output.

example

string : ‘json’ | ‘markdown’

To get the output in a specified format.

example

Configtest

Validate a webpack configuration.

example

Config Path

Serve

Run the webpack dev server.

example

Watch

Run webpack and watch for files changes.

example

Flags

By default webpack ships with the following flags:

Negated Flags

FlagDescription
—no-colorDisables any color on the console
—no-hotDisables hot reloading if you have it enabled via your config
—no-statsDisables any compilation stats emitted by webpack
—no-watchDo not watch for file changes
—no-devtoolDo not generate source maps
—no-watch-options-stdinDo not stop watching when stdin stream has ended

Core Flags

Starting CLI v4 and webpack v5, CLI imports the entire configuration schema from webpack core to allow tuning almost every configuration option from the command line.

Usage

With configuration file

See configuration for the options in the configuration file.

Without configuration file

example

entry

output-path

Example

This will form the bundle with both the files as separate entry points.

Default Configurations

CLI will look for some default configurations in the path of your project, here are the config files picked up by CLI.

This is the lookup priority in increasing order

Common Options

warning

List basic commands and flags available on the cli

List all supported commands and flags by cli

See help for a specific command or option

version

Show version of installed packages and sub-packages

To inspect the version of webpack and webpack-cli you are using, run the command:

This will output the following result:

It will output the version of webpack-dev-server as well if you have it installed:

To inspect the version of any webpack-cli sub-package (like @webpack-cli/info ), run command similar to the following:

This will output the following result:

config

Build source using a configuration file

config-name

Consider the following webpack.config.js :

To run only the second configuration:

You can also pass multiple values:

merge

Print result of webpack as JSON

In every other case, webpack prints out a set of stats showing bundle, chunk and timing details. Using this option, the output can be a JSON object. This response is accepted by webpack’s analyse tool, or chrisbateman’s webpack-visualizer, or th0r’s webpack-bundle-analyzer. The analyse tool will take in the JSON and provide all the details of the build in graphical form.

See the stats data api to read more about the stats generated here.

Environment Options

When the webpack configuration exports a function, an «environment» may be passed to it.

See the environment variables guide for more information on its usage.

In addition to the customized env showed above, there are some built-in ones under env to be used inside your webpack configuration:

Note that you can not access those built-in environment variables inside the bundled code.

node-env

Configuration Options

ParameterExplanationInput typeDefault
—configPath to the configuration filestring[]Default Configs
—config-nameName of the configuration to usestring[]
—envEnvironment passed to the configuration, when it is a functionstring[]

Analyzing Bundle

warning

Make sure you have webpack-bundle-analyzer installed in your project else CLI will prompt you to install it.

Progress

Pass CLI arguments to Node.js

To pass arguments directly to Node.js process, you can use the NODE_OPTIONS option.

For example, to increase the memory limit of Node.js process to 4 GB

Also, you can pass multiple options to Node.js process

Exit codes and their meanings

Exit CodeDescription
0Success
1Errors from webpack
2Configuration/options problem or an internal error

CLI Environment Variables

WEBPACK_PACKAGE

Use a custom webpack version in CLI. Considering the following content in your package.json :

To use webpack v4.0.0 :

To use webpack v5.32.0 :

Troubleshooting

You might encounter this error in the case of using native ESM in TypeScript (i.e. type: «module» in package.json ).

To fix the error above use the following command:

Development

This guide extends on code examples found in the Output Management guide.

If you’ve been following the guides, you should have a solid understanding of some of the webpack basics. Before we continue, let’s look into setting up a development environment to make our lives a little easier.

warning

The tools in this guide are only meant for development, please avoid using them in production!

webpack.config.js

Using source maps

There are a lot of different options available when it comes to source maps. Be sure to check them out so you can configure them to your needs.

For this guide, let’s use the inline-source-map option, which is good for illustrative purposes (though not for production):

webpack.config.js

Now let’s make sure we have something to debug, so let’s create an error in our print.js file:

src/print.js

Now open the resulting index.html file in your browser. Click the button and look in your console where the error is displayed. The error should say something like this:

We can see that the error also contains a reference to the file ( print.js ) and line number (2) where the error occurred. This is great because now we know exactly where to look in order to fix the issue.

Choosing a Development Tool

warning

Some text editors have a «safe write» function that might interfere with some of the following tools. Read Adjusting Your Text Editor for a solution to these issues.

It quickly becomes a hassle to manually run npm run build every time you want to compile your code.

There are a couple of different options available in webpack that help you automatically compile your code whenever it changes:

Using Watch Mode

You can instruct webpack to «watch» all files within your dependency graph for changes. If one of these files is updated, the code will be recompiled so you don’t have to run the full build manually.

Let’s add an npm script that will start webpack’s Watch Mode:

package.json

Now run npm run watch from the command line and see how webpack compiles your code. You can see that it doesn’t exit the command line because the script is currently watching your files.

Now, while webpack is watching your files, let’s remove the error we introduced earlier:

src/print.js

Now save your file and check the terminal window. You should see that webpack automatically recompiles the changed module!

The only downside is that you have to refresh your browser in order to see the changes. It would be much nicer if that would happen automatically as well, so let’s try webpack-dev-server which will do exactly that.

Using webpack-dev-server

The webpack-dev-server provides you with a rudimentary web server and the ability to use live reloading. Let’s set it up:

Change your configuration file to tell the dev server where to look for files:

webpack.config.js

The optimization.runtimeChunk: ‘single’ was added because in this example we have more than one entrypoint on a single HTML page. Without this, we could get into trouble described here. Read the Code Splitting chapter for more details.

warning

webpack-dev-server doesn’t write any output files after compiling. Instead, it keeps bundle files in memory and serves them as if they were real files mounted at the server’s root path. If your page expects to find the bundle files on a different path, you can change this with the devMiddleware.publicPath option in the dev server’s configuration.

Let’s add a script to easily run the dev server as well:

package.json

Now we can run npm start from the command line and we will see our browser automatically loading up our page. If you now change any of the source files and save them, the web server will automatically reload after the code has been compiled. Give it a try!

The webpack-dev-server comes with many configurable options. Head over to the documentation to learn more.

Now that your server is working, you might want to give Hot Module Replacement a try!

Using webpack-dev-middleware

webpack-dev-middleware is a wrapper that will emit files processed by webpack to a server. This is used in webpack-dev-server internally, however it’s available as a separate package to allow more custom setups if desired. We’ll take a look at an example that combines webpack-dev-middleware with an express server.

Let’s install express and webpack-dev-middleware so we can get started:

Now we need to make some adjustments to our webpack configuration file in order to make sure the middleware will function correctly:

webpack.config.js

project

server.js

Now add an npm script to make it a little easier to run the server:

package.json

If you would like to know more about how Hot Module Replacement works, we recommend you read the Hot Module Replacement guide.

Adjusting Your Text Editor

When using automatic compilation of your code, you could run into issues when saving your files. Some editors have a «safe write» feature that can potentially interfere with recompilation.

To disable this feature in some common editors, see the list below:

Conclusion

Now that you’ve learned how to automatically compile your code and run a development server, you can check out the next guide, which will cover Code Splitting.

Источники информации:

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

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