webpack - 如何在当前 webpack 配置目录之外构建 dist 文件夹

webpack - how to build dist folder outside current webpack config directory

这是我当前的项目目录

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

package.json

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

当我 运行 npm run build 时,dist 文件夹在我的 webpack 目录中创建。

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

我要的是

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

这是我的 webpack 配置

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" }),
  ],
});

您可以为 output.path 配置指定 绝对 路径。

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",
  },
});

运行 npm run build 在项目的根路径中。

输出:

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