K
K
Kirill Karpik2019-08-25 17:04:44
webpack
Kirill Karpik, 2019-08-25 17:04:44

How to connect and correctly split libraries into chunks?

Hello. I am learning webpack. There are several entry files and libraries, some are only included on one page and others on multiple pages. I would like to connect everything as rationally as possible: each page connects its own script (index.html with index.js, about.html with about.js, etc.), libraries connected on each page (for example, jquery), combined into vendor.js or something leave something like that and libraries that are connected individually (for example, moment) in separate files (or quite smartly - create files with libraries that are used only in pairs).

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

const PAGES_DIR = `${PATHS.src}/html`;
const PAGES = fs.readdirSync(PAGES_DIR);

module.exports = {
  entry: {
    a: "./src/js/a.js",
    b: "./src/js/b.js",
    c: "./src/js/c.js"
  },
  output: {
    filename: "./assets/js/[name].[hash].js",
    path: "./dist",
    publicPath: "/"
  },
  optimization: {
    runtimeChunk: "single",
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          filename: `./assets/js/[name].[hash].js`,
          chunks: 'all'
        }
      },
    },
  },
  module: {
    rules: [
      // все загрузчики
    ]
  },
  plugins: {
    // вспомогательные плагины
    new webpack.providePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery",
    }),
    ...PAGES.map(page => new HtmlWebpackPlugin({
      template: `${PAGES_DIR}/${page}`
    }))
  }
}

I would be happy with any implementation method (including ways to do it differently, which will still be good from the technical side).

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question