如何为 npm 运行 build 使用绝对路径

How to Use Absolute Path for npm run build

所以对于我的 ReactJs 项目,我使用绝对路径导入,就像这样 import {button} from /buttons

而不是这样的相对路径: import {button} from ../../buttons

它在 npm start 上运行良好,但是当我尝试使用 npm run build 构建时,出现以下错误:

ERROR in ./src/Admin/Setting/Components/StepTwo.js 25:0-54
Module not found: Error: Can't resolve 'assets/theme/logoicon/edit.png' in 'C:\Users\nayeer\source\repos\project\src\Admin\Setting\Components'
 @ ./src/Admin/Setting/index.js 3:0-43 16:59-66
 @ ./src/Admin/Setting/index.js 175:0-92 685:15-30
 @ ./src/AdminLayout/AppMain/index.js
 @ ./src/Admin/MainAdmin/index.js 29:0-48 187:46-53
 @ ./src/index.js 7:0-42 62:10-19

如何使用相对路径构建项目?

这是我的 jsconfig.json :

{
  "compilerOptions": {
    "baseUrl": "./src"
  },
  "include": ["src"]
}

这是我的webpack.config.js。我在 resolve.alias 中添加了我的基础文件夹 src 但它似乎没有用:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const WorkboxWebpackPlugin = require("workbox-webpack-plugin");

const isProduction = process.env.NODE_ENV == "production";

const stylesHandler = isProduction
  ? MiniCssExtractPlugin.loader
  : "style-loader";

const config = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "build"),
  },
  devServer: {
    open: true,
    host: "localhost",
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "index.html",
    }),

    // Add your plugins here
    // Learn more about plugins from https://webpack.js.org/configuration/plugins/
  ],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/i,
        loader: "babel-loader",
      },
      {
        test: /\.s[ac]ss$/i,
        use: [stylesHandler, "css-loader", "postcss-loader", "sass-loader"],
      },
      {
        test: /\.css$/i,
        use: [stylesHandler, "css-loader", "postcss-loader"],
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
        type: "asset",
      },

      // Add your rules for custom modules here
      // Learn more about loaders from https://webpack.js.org/loaders/
    ],
  },
  resolve: {
    alias: {
      Components: path.resolve(__dirname, 'src')
    }
  },
};

module.exports = () => {
  if (isProduction) {
    config.mode = "production";

    config.plugins.push(new MiniCssExtractPlugin());

    config.plugins.push(new WorkboxWebpackPlugin.GenerateSW());
  } else {
    config.mode = "development";
  }
  return config;
};

在 Webpack 配置文件中,添加 resolve.alias 以便更容易地创建别名和导入模块。

module.exports = {
  //...
  resolve: {
    alias: {
      Components: path.resolve(__dirname, 'src/components/')
    }
  }
}

例如,src/components/ 中的所有模块现在都可以使用绝对路径。

并为 VS code 识别 path

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "components/*": ["src/components/*"]
    }
  },
  "exclude": ["node_modules"] 
}