React项目使用rss-parser遇Module not found,如何配置resolve.fallback?
问题描述
在React项目中使用rss-parser库,安装后编写了如下代码:
import Parser from 'rss-parser'; let parser = new Parser(); (async () => { let feed = await parser.parseURL('https://www.reddit.com/.rss'); console.log(feed.title); feed.items.forEach(item => { console.log(item.title + ':' + item.link) }); })();
运行后抛出错误:
ERROR in ./node_modules/rss-parser/lib/parser.js 3:13-28 Module not found: Error: Can't resolve 'http' in '\node_modules\rss-parser\lib' BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }' - install 'stream-http' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "http": false }
请问resolve.fallback的配置信息应该设置在何处?
解决方法
resolve.fallback是Webpack配置中的核心选项,具体配置位置取决于你的React项目使用的构建工具:
1. Create React App 默认脚手架
Create React App默认隐藏Webpack配置,需借助第三方工具修改:
- 安装配置工具
craco:npm install @craco/craco --save-dev - 在项目根目录创建
craco.config.js,添加配置:module.exports = { webpack: { configure: { resolve: { fallback: { // 需要polyfill时配置 "http": require.resolve("stream-http"), // 不需要polyfill时配置 // "http": false } } } } }; - 修改
package.json中的启动脚本,替换react-scripts为craco:"scripts": { "start": "craco start", "build": "craco build", "test": "craco test" }
2. 自定义Webpack配置 eject后或手动配置的项目
如果项目已有webpack.config.js文件,直接在配置的resolve节点下添加fallback:
module.exports = { // 其他配置项... resolve: { fallback: { "http": require.resolve("stream-http"), // 或设置为false // 注意:rss-parser可能还依赖其他Node核心模块,需同步配置 "https": require.resolve("https-browserify"), "url": require.resolve("url/") } } };
之后安装对应的polyfill依赖包:
npm install stream-http https-browserify url --save-dev
3. Vite项目
Vite项目需通过插件处理Node核心模块的polyfill:
- 安装
vite-plugin-node-polyfills插件:npm install vite-plugin-node-polyfills --save-dev - 在
vite.config.js中配置插件:import { nodePolyfills } from 'vite-plugin-node-polyfills'; export default { plugins: [ nodePolyfills({ include: ['http', 'https', 'url'] }) ] };
内容的提问来源于stack exchange,提问作者matdev
相关产品推荐
相关产品推荐

