如何在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
相关产品推荐
相关产品推荐

