You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Webpack中设置preferRelative选项?解决模块导入报错

解决Webpack 5解析不带./的相对路径问题

你遇到的报错是因为Webpack默认会优先去node_modules查找不带路径前缀的模块,而非当前目录。按照提示启用resolve.preferRelative即可解决,无需修改源码里的导入路径。

设置方法

直接在你的webpack.config.js的resolve配置对象中添加preferRelative: true即可,修改后的完整配置如下:

const path = require("path");
const WebpackNotifierPlugin = require("webpack-notifier");
const BrowserSyncPlugin = require("browser-sync-webpack-plugin");

module.exports = {
  entry: ["babel-polyfill", "./src/index.js"],
  output: {
    path: path.resolve(__dirname, "./dist"),
    filename: "bundle.js",
  },
  watch: true,
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
    ],
  },
  devtool: "inline-source-map",
  plugins: [new WebpackNotifierPlugin(), new BrowserSyncPlugin()],
  resolve: {
    extensions: [".js", ".jsx", ".ts"],
    // 添加该行,让Webpack优先在当前目录解析不带./的模块
    preferRelative: true,
  },
};

原理说明

preferRelative: true会让Webpack在遇到类似import App from 'App'的请求时,先尝试在当前文件所在目录下查找App.js/App.jsx等匹配扩展名的文件,而非直接去node_modules中查找,完美适配你之前的导入习惯。

内容的提问来源于stack exchange,提问作者user19615984

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:55:45