Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Webpack output bundle

Im new to React development with Webpack having set up a boilerplate by following this tutorial article.

I get the jist of how webpack works and can follow along with the article but having trouble understanding how my particular webpack.config.js is creating the files and bundles that it does and how to modify these to achieve some custom function.

webpack.config.js

const HtmlWebPackPlugin = require("html-webpack-plugin");
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader"
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html"
    })
  ],
  mode: 'development'
};  

I understand that the rules object grabs all .js files (excluding those in node_modules) and compiles them to standard JS using babel. Then it grabs all the .html files and creates an html file including the bundle using html-loader. The HtmlWebPackPlugin is implemented here. Mode indicates to create a development version of the bundle.

My folder structure is as follows:

- /dist (generated by webpack)
    - index.html
    - main.js (webpack bundle)
- /src (created manually)
  - /components
    - components.js (react components)
  - index.html
  - index.js
- .babelrc
- package.json (npm init -y)
- webpack.config.js (manually configured)

Questions:

  1. Webpack creates the /dist directory and the files contained in it. Where in the configuration is it indicated that this directory be named "dist" and the main bundle file be named main.js?
  2. Where is it indicated that /dist be at the root of the project. Suppose I wanted the directory to be named foo and placed two levels up (../../foo/)
  3. In webpack.config.js the "rules" object has keys defined as test to indicate which files types to bundle. test: /\.js$/, & test: /\.html$/ Is "test" an arbitrary value or a default webpack configuration key.

I was looking at these docs with regard to webpack configuration but the syntax was very different from what is shown here.

like image 695
yevg Avatar asked Feb 02 '26 00:02

yevg


1 Answers

1 & 2:

you can set output config like this:

  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  • filename

name of output bundle file. default: main.js

  • path

    location of save output files. default: /dist

to get root of project you have to use path!

import path:

var path = require('path');

and use like this:

path.resolve(__dirname, DIRECTORY_NAME)

3: test is default webpack configuration key and its to specify that loader file type support like html-loader.

like image 126
Soroush Chehresa Avatar answered Feb 04 '26 12:02

Soroush Chehresa