Шпаргалка по Webpack


Оглавление

Шпаргалка по Webpack

  • Установка

  • Загрузчики [для импорта материала]

  • Плагины [для выполнения действий]

  • Сборки для разработки и производства

  • Многостраничные приложения

  • Дополнительные возможности [добавление bootstrap, font awesome]

  • ES Lint


Webpack Cheatsheet

Ссылка на Awesome Webpack Boilerplate : Athlon Webpack boilerplate

Коллекция всех моих таблиц находится на Github

Установка

npm install webpack webpack-cli --save-dev
Войти в полноэкранный режим Выход из полноэкранного режима
//webpack.config.js
const path = require("path");

module.exports = {
   entry: "./src/index.js",
   output: {
      filename: "bundle.js",
      path: path.resolve(__dirname, "./dist"),
   },
   mode: "none",
};
Войти в полноэкранный режим Выход из полноэкранного режима

Используя Webpack, мы теперь можем экспортировать и импортировать данные и файлы между собой.


Загрузчики

Библиотеки, которые помогают импортировать данные с помощью webpack.

Добавление изображений

npm install file-loader --save-dev
Вход в полноэкранный режим Выход из полноэкранного режима
//webpack.config.js
module.exports = {
   entry: "./src/index.js",
   output: {
      filename: "bundle.js",
      path: path.resolve(__dirname, "./dist"),
      publicPath: "", /* to specify image location for html , website URL in production */
   },
   mode: "none",
   module: {
      rules: [
         {
            test: /.(png|jpg)$/,
            use: ["file-loader"],
         },
      ],
   },
};
Войти в полноэкранный режим Выход из полноэкранного режима
//index.js
import Kiwi from "./kiwi.jpg";
Войти в полноэкранный режим Выход из полноэкранного режима

Добавление CSS в JS

npm install style-loader css-loader --save-dev
Войти в полноэкранный режим Выход из полноэкранного режима
//webpack.config.js
{
    test: /.css$/,
    use: ["style-loader", "css-loader"],
},
Войти в полноэкранный режим Выход из полноэкранного режима
//component.js
import "./hello-world-button.css";
Войти в полноэкранный режим Выход из полноэкранного режима

Добавление SCSS

npm install sass-loader sass --save-dev
Войти в полноэкранный режим Выход из полноэкранного режима
//webpack.config.js
{
    test: /.scss$/,
    use: ["style-loader", "css-loader", "sass-loader"], //first style-loader at last sass-loader
},
Войти в полноэкранный режим Выход из полноэкранного режима
//component.js
import "./hello-world-button.scss";
Войти в полноэкранный режим Выход из полноэкранного режима

Добавление Babel

npm install @babel/core babel-loader @babel/preset-env babel-plugin-transform-class-properties --save-dev
Войти в полноэкранный режим Выйти из полноэкранного режима
//webpack.config.js
{
    test: /.js$/,
    exclude: /node_modules/,
    use: {
        loader: "babel-loader",
        options: {
            presets: ["@babel/env"],
            plugins: ["transform-class-properties"],
        },
    },
},
Войти в полноэкранный режим Выход из полноэкранного режима

Плагины

Плагины выполняют определенные действия над импортированным материалом

Минифицировать JS

npm install terser-webpack-plugin --save-dev
Войти в полноэкранный режим Выход из полноэкранного режима
//webpack.config.js
const TerserPlugin = require("terser-webpack-plugin");

/* Inside Module.exports */
plugins: [new TerserPlugin()],
Войти в полноэкранный режим Выход из полноэкранного режима

Извлечение CSS в определенный файл

npm install mini-css-extract-plugin --save-dev
Войти в полноэкранный режим Выход из полноэкранного режима
//webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    rules = [
        {
            test: /.css$/,
            use: [MiniCssExtractPlugin.loader, "css-loader"],
        },
        {
            test: /.scss$/,
            use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
        },
    ]
}

plugins: [
    new MiniCssExtractPlugin({
        filename: "style.css",
    }),
],
Войти в полноэкранный режим Выход из полноэкранного режима

Генерировать новое имя файла при каждом выполнении (только при изменении содержимого)

//simple add [contenthash] to the filename you want to have new name
filename: "bundle.[contenthash].js",
Войти в полноэкранный режим Выйти из полноэкранного режима

Удаление старых файлов и рендеринг новых при каждой сборке

npm install clean-webpack-plugin --save-dev
Войти в полноэкранный режим Выйти из полноэкранного режима
//webpack.config.js

const { CleanWebpackPlugin } = require("clean-webpack-plugin");

// Running This PLugin without option , will automatically clean dist folder

plugins: [
    new CleanWebpackPlugin({
        cleanOnceBeforeBuildPatterns: [
            "**/*",  //this runs by default in dist folder
            path.join(process.cwd(), "build/**/*"), //adding other folders
        ],
    }),
],
Войти в полноэкранный режим Выход из полноэкранного режима

Генерация HTML с помощью Webpack

npm install html-webpack-plugin --save-dev 
Войти в полноэкранный режим Выход из полноэкранного режима
//webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin");

plugins: [
    new HtmlWebpackPlugin(), //generates default html file
]

//publicPath can be empty as html is generated in the same place as other files by default. (the path specified)
Войти в полноэкранный режим Выход из полноэкранного режима

— Указание параметров HTML вручную

new HtmlWebpackPlugin({  //extra options for the html file
    title: "Hello World",
    filename: "subfolder/custom_filename.html",
    meta: {
        description: "Some Description",
    },
}),
Войти в полноэкранный режим Выход из полноэкранного режима

— Использование механизма шаблонов HTML (HandleBars)

npm install handlebars-loader --save-dev
npm install handlebars --save
Вход в полноэкранный режим Выход из полноэкранного режима
// Add a Test in module rules for hbs files to use handlebars loader
{
    test: /.hbs$/,
    use: ["handlebars-loader"],
}

//Also add the new plugin to access hbs
new HtmlWebpackPlugin({
    title: "Hello World",
    template: "src/index.hbs",
    description: "Some Description",
}),
Войти в полноэкранный режим Выход из полноэкранного режима

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

Изменение режима

//webpack.config.js
module.exports = {
    mode : "production", //for production (here no source or anything is done)
    mode : "development", //source maps are rendered and development is faster
    mode : "none" //to not use any mode
}
Войти в полноэкранный режим Выход из полноэкранного режима

Создание разных конфигураций для разных режимов

  • Сохраните конфигурацию Webpack в разных файлах, изменив режим в обоих.
  • затем создайте скрипты npm для определенных файлов
//package.json

"scripts": {
    "build": "webpack --config webpack.production.config.js",
    "dev": "webpack --config webpack.dev.config.js"
  },
Вход в полноэкранный режим Выход из полноэкранного режима

Использование Webpack-dev-server в режиме разработки

npm install webpack-dev-server --save-dev
Войти в полноэкранный режим Выход из полноэкранного режима
//webpack.dev.config.js

module.exports = {
    devServer: {
         contentBase : path.resolve(__dirname, "./dist"),
         index: 'index.html',
         port: 9000
   }
}
Войти в полноэкранный режим Выход из полноэкранного режима
//package.json

scripts = {
    "dev": "webpack-dev-server --config webpack.dev.config.js --hot"
}
Войти в полноэкранный режим Выход из полноэкранного режима

Многостраничные приложения

Рендеринг нескольких страниц

//webpack.production.config.js

module.exports = {
    entry: {
        'hello-world': './src/hello-world.js', //file 1
        'kiwi': './src/kiwi.js', // file 2
    },
    output: {
        filename: "[name].[contenthash].js", //will generate different names
        path: path.resolve(__dirname, "./dist"),
        publicPath: "",
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "[name].[contenthash].css", //same for css files
        }),
        new HtmlWebpackPlugin({
         filename: 'hello-world.html', //different Html Files
         chunks: ['hello-world'], //is used from entry point
         title: "Hello World",
         description: "Hello World",
         template: "src/page-template.hbs",
      }),
      new HtmlWebpackPlugin({
         filename: 'kiwi.html',
         chunks: ['kiwi'], //specify only the ones u need
         title: "Kiwi",
         description: "Kiwi",
         template: "src/page-template.hbs",
      }),
    ]
}
Войти в полноэкранный режим Выход из полноэкранного режима

Создание общего файла для зависимостей

//webpack.production.config.js

module.exports = {
    optimization: {
        splitChunks: {
            chunks: "all", //this will integrate all the extra packages into one extra js file 
            minSize : 10000, //this specifies the minimum size of the bundle to split
             automaticNameDelimiter: '_' //this specifies the separation between file names , by default ~
        }
    },  
    plugins : [
        new HtmlWebpackPlugin({
            chunks: ['hello-world'],
        }),
        new HtmlWebpackPlugin({
            chunks: ['kiwi'],
        }),
    ] // integrating the extra modules js file into the HTML 

}
Вход в полноэкранный режим Выход из полноэкранного режима

Дополнительные возможности

Добавление пользовательских шрифтов

//webpack.config.js
{
    test: /.{woff2|woff}$/,
    use: [
        {
            loader: 'file-loader',
            options: {
                name: '[name].[ext]',
                outputPath: 'fonts/',
            }
        }
    ],
}

//add font face in scss 
//import scss in js
Войти в полноэкранный режим Выйти из полноэкранного режима

Добавление Bootstrap

npm install bootstrap jquery popper.js --save
Войти в полноэкранный режим Выйти из полноэкранного режима
  • Использование Bootstrap без его редактирования
import "bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
Войти в полноэкранный режим Выйти из полноэкранного режима
  • Использовать прекомпилированный Bootstrap
npm install postcss-loader precss autoprefixer --save-dev
Войти в полноэкранный режим Выйти из полноэкранного режима
//webpack.config.js

test: /.scss$/,
    use: [
        MiniCssExtractPlugin.loader,
        "css-loader",
        {
            loader: "postcss-loader",
            options: {
                plugins: function () {
                    return [require("precss"), require("autoprefixer")];
                },
            },
        },
        "sass-loader",
    ],
Войти в полноэкранный режим Выйти из полноэкранного режима
//index.scss
@import "~bootstrap/scss/bootstrap";
Войти в полноэкранный режим Выход из полноэкранного режима

Добавление Font Awesome

  • Установка основных пакетов для включения только необходимых иконок в конечный пакет
npm install --save-dev @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/free-regular-svg-icons @fortawesome/free-brands-svg-icons
Вход в полноэкранный режим Выход из полноэкранного режима
//index.js

import { library, dom } from "@fortawesome/fontawesome-svg-core";
//library is used to import the specific icon , dom replaces i tag in DOM
import { faSpinner } from "@fortawesome/free-solid-svg-icons";
// import only the icons needed 


library.add(faSpinner); //puts the icon in the library
dom.watch(); //watches for changes in the html, and replaces every font awesome <i> tag
Войти в полноэкранный режим Выход из полноэкранного режима
<!-- index.html -->

<i class="fas fa-spinner fa-spin"></i> 
<!-- simply consume the icon needed -->
Войти в полноэкранный режим Выход из полноэкранного режима

ES Lint

  • Этот файл определяет основные правила для проверки ошибок в js, особенно используется для линтинга и обеспечения универсального использования стандарта.
npm install eslint babel-eslint --save-dev
Войти в полноэкранный режим Выйти из полноэкранного режима
  • создать .eslintrc.json (может быть сгенерирован, смотрите документацию)
{
    "extends": "eslint:recommended", //recommended settings
    "parser": "babel-eslint", // babel for classes
    "parserOptions": { //for es6 import and others
        "ecmaVersion": 6,
        "sourceType": "module"
    }, 
    "env": {
        "node": true, //tells we are using node , for "require"
        "browser": true //tells running in browser , for "document"
    },
    "rules": { //specific rules that we want to add
        "no-console": 0
    }
}
Войдите в полноэкранный режим Выход из полноэкранного режима
  • вручную запустите eslint с помощью eslint .
  • или установите специальные плагины Linter в ваш редактор, чтобы получить ошибки во время кодирования.

Оцените статью
Procodings.ru
Добавить комментарий