How to configure different directories for outputted JS file in Webpack?

Viewed 20

I'm working on a WordPress plugin and have a file structure like this:

/public/
  /js/
    /modules/
    /public.bundled.js // how to output public here?
/admin/
  /js/
    /modules/
    /admin.bundled.js //how to output admin here?

I'm incorporating webpack into the development process and want to output the bundled files into their respective directories, but am new to Webpack and not sure how to achieve this. Here's my config:

const path = require("path");
module.exports = {
  entry: {
    public: __dirname + "/public/js/modules/public.js",
    admin: __dirname + "/admin/js/modules/admin.js",
  },
  output: {
    filename: "[name].bundled.js",
    path: // Not sure how to achieve this. Any ideas?
  },
  mode: "development",
  watch: true,
};

Any ideas how to achieve what I'm looking for? Thank you in advance.

1 Answers

I assume you use the latest version of webpack@5.x so if you look at its document on entry, you might notice that you can define your each entry file as output filename. In short, your configuration looks like:

module.exports = {
  entry: {
    public: {
      import: './public/js/modules/public.js',
      filename: 'public/js/modules/public.bundled.js',
    },
    // ...others
  },
  output: {
    // your root dir
    path: __dirname,
    // ...
  },
  // ...
};

Related