How to put entry name in chunk filename? (webpack)

965 views Asked by At

My files:

page1.js

import nameFunction from "./nameHelper"

page2.js

import nameFunction from "./nameHelper"
import users from "./users"

page3.js

import users from "./users"

What I get:

│   package.json
│   page1.html
│   webpack.config.js
│
├───dist
│   └───scripts
│           page1.js
│           page2.js
│           page3.js
│           Scripts_js_nameHelper_js.js
│           Scripts_js_users_js.js
└───Scripts
    └───js
            nameHelper.js
            page1.js
            page2.js
            page3.js
            users.js

What I want:

├───dist
│   └───scripts
│           page1.js
│           page2.js
│           page3.js
│           page1_page2_nameHelper.js
│           page2_page3_users.js

Webpack 5 config:

module.exports = {
  entry: {
    page1: "./Scripts/js/page1.js",
    page2: "./Scripts/js/page2.js",
    page3: "./Scripts/js/page3.js",
  },

  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, dirName),
  },
  // devtool: "source-map",
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules|bower_components/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
  },
  plugins: [new CleanWebpackPlugin()],
  optimization: {
    splitChunks: {
      chunks: "all",
      minSize: 0
    },
  },
};

I need this to easily add all related files to the script tag in my .NET MVC pages.

<script type="text/javascript" asp-src-include="~/dist/*page1_*.js"></script>

Unless there is another solution to add only one js file to the script tag on the page. I really dislike using HtmlWebpackPlugin and working with template files, not directly with .cshtml file.

<script type="text/javascript" src="~/page1.js"></script>

Because the entry file for each page will be unchanged and the chunk files will keep changing names and quantity - constantly.

0

There are 0 answers