Home > Mobile >  webpack - how to build dist folder outside current webpack config directory
webpack - how to build dist folder outside current webpack config directory

Time:11-26

This is my current project directory

src
  -App.jsx
  -...
webpack
  -webpack.base.js
  -webpack.prod.js

package.json

  "scripts": {
    "build": "webpack --config ./webpack/webpack.prod.js",
  }

When I run npm run build, the dist folder is created inside my webpack directory.

src
  -App.jsx
  -...
webpack
  -dist
  -webpack.base.js
  -webpack.prod.js

What I want is

dist
src
  -App.jsx
  -...
webpack
  -webpack.base.js
  -webpack.prod.js

This is my webpack config

webpack.base.js

const webpack = require("webpack");

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

module.exports = {
  entry: "./src/index.jsx",
  resolve: {
    extensions: ["*", ".js", ".jsx"],
    fallback: {...},
  },
  module: {
    rules: [...],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "public/index.html",
      filename: "index.html",
      favicon: "public/favicon.ico",
    }),
    new webpack.ProvidePlugin({
      Buffer: ["buffer", "Buffer"],
    }),
    new webpack.ProvidePlugin({
      process: "process/browser",
    }),
  ],
};

webpack.prod.js

const { merge } = require("webpack-merge");
const base = require("./webpack.base");
const path = require("path");

const Dotenv = require("dotenv-webpack");

module.exports = merge(base, {
  mode: "production",
  devtool: "inline-source-map", //For dev only
  output: {
    path: path.join(__dirname, "/dist"),
    filename: "bundle.js",
  },
  plugins: [
    new Dotenv({ path: "./.env.production" }),
  ],
});

CodePudding user response:

You can specify an absolute path for output.path configuration.

webpack/webpack.prod.js:

const { merge } = require("webpack-merge");
const base = require("./webpack.base");
const path = require("path");

module.exports = merge(base, {
  mode: "production",
  devtool: "inline-source-map",
  output: {
    path: path.join(__dirname, "../dist"),
    filename: "bundle.js",
  },
});

Run npm run build in root path of the project.

Output:

⚡  tree -L 2 -I 'node_modules'               
.
├── dist
│   └── bundle.js
├── package-lock.json
├── package.json
├── src
│   └── index.jsx
└── webpack
    ├── webpack.base.js
    └── webpack.prod.js
  • Related