2024-08-24

本文面向在使用 Vue(含 Vue CLI / webpack / Vite) 开发时遇到 “BREAKING CHANGE: webpack < 5 used to include polyfills…” 或 “Buffer is not defined / process is not defined / 不能解析 Node core modules” 等错误的工程师。文章包含原理解释、常见场景、逐步修复方案(可复制的代码片段)、以及针对 Vue CLI、纯 webpack、和 Vite 的具体配置示例、调试要点与替代方案,方便你快速上手并彻底解决问题。关键结论与改法在正文中并带来源引用,便于深入查证。(webpack)


摘要(为什么会报这个错?)

Webpack 5 取消了对 Node.js 核心模块(如 crypto, stream, path, os, buffer, process 等)的自动浏览器端 polyfill。旧版本(webpack < 5)在构建浏览器包时会自动提供这些 polyfills;升级到 webpack 5 后,若你的依赖(或其依赖)在浏览器端仍然 require('crypto') 或使用 Buffer / process,构建就会报错并提示需要手动配置 polyfill 或显式禁用(false)。这就是报错的根源:缺少 polyfill。(GitHub)


目录

  1. 发生场景与典型错误提示
  2. 可选策略总览(短)
  3. 方案 A:使用 node-polyfill-webpack-plugin(最简单)
  4. 方案 B:手动配置 resolve.fallback + ProvidePlugin(更可控)
  5. Vue CLI 项目:在 vue.config.js 中做改动(示例)
  6. Vite(Vue 3 + create-vue):如何处理(替代方式)
  7. 常见模块的替代包与安装命令(一键清单)
  8. 调试与验证(如何确认已生效)
  9. 性能与包体积注意事项
  10. 真实案例与常见陷阱(FAQ)
  11. 总结与推荐

1. 发生场景与典型错误提示

你可能在以下情形遇到问题:

  • 在 Vue 项目中 npm run serve / npm run build 报错:
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.
  • 浏览器运行时报 ReferenceError: Buffer is not definedprocess is not defined、或模块无法解析 cryptostream 等。
  • 升级 Vue CLI(或依赖)并迁移到 webpack 5 后出现。(GitHub)

这类错误说明:某处代码(你直接写的或第三方库)使用了 Node.js 的核心 API,而 webpack 5 默认不再自动提供这些在浏览器环境下的实现。


2. 可选策略总览(短)

面对这问题,你有几条可选策略(从简单到复杂):

  1. 为 webpack 添加一键 polyfill 插件node-polyfill-webpack-plugin(最省心)。(NPM)
  2. 手动配置 resolve.fallback + ProvidePlugin:显式控制需要哪些模块与别名(更精细)。(Stack Overflow)
  3. 如果不需要这些模块:在 resolve.fallback 中将其设为 false,以减小包体积(告诉 webpack 此模块在浏览器不需要)。(Reddit)
  4. 对于 Vite / Rollup:使用对应的 polyfill 插件或在入口处手动 shim(例如 import { Buffer } from 'buffer'; window.Buffer = Buffer)。(GitHub)

下面逐一给出具体做法与可复制配置。


3. 方案 A:使用 node-polyfill-webpack-plugin(最简单)

适用场景:只想快速修好构建、项目使用 webpack 5(包括 Vue CLI 5 使用的 webpack 5),不想逐个列出 fallback。

步骤

  1. 安装插件与常见 polyfill 包(插件会帮你引入需要的 polyfills):
npm install --save-dev node-polyfill-webpack-plugin
# 或者 yarn add -D node-polyfill-webpack-plugin
  1. 在你的 webpack.config.js 中引入并启用:
// webpack.config.js
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');

module.exports = {
  // ... 你的其它 webpack 配置 ...
  plugins: [
    new NodePolyfillPlugin()
  ]
};

说明:该插件会自动添加常用 Node 核心模块的 polyfills,快速解决大多数因缺少 polyfill 导致的构建报错。适合快速修复或调试。(NPM)


4. 方案 B:手动配置 resolve.fallback + ProvidePlugin(更可控,推荐生产环境)

适用场景:你希望精确地控制哪些模块被 polyfill、哪些不被 polyfill,以减小体积或避免引入不必要的代码时使用。

4.1 安装常用 polyfill 包

常见替代实现(npm 包名):

  • buffer(Buffer)
  • stream-browserify(stream)
  • crypto-browserify(crypto)
  • path-browserify(path)
  • os-browserify(os)
  • assert(assert)
  • util(util)
  • process(process/browser)

安装示例(可一次性安装常见项):

npm install --save buffer stream-browserify crypto-browserify path-browserify os-browserify assert util process
注:有些包名后面需要加 /browser 版本(例如 buffer/),下文配置会示例。

4.2 webpack 配置(示例)

把下面的片段合并到你的 webpack.config.js(或 vue.config.jsconfigureWebpack)中:

const webpack = require('webpack');

module.exports = {
  // ... 其他配置 ...
  resolve: {
    fallback: {
      "buffer": require.resolve("buffer/"),
      "stream": require.resolve("stream-browserify"),
      "crypto": require.resolve("crypto-browserify"),
      "path": require.resolve("path-browserify"),
      "os": require.resolve("os-browserify/browser"),
      "assert": require.resolve("assert/"),
      "util": require.resolve("util/"),
      // 如果不想 polyfill 某个模块,可以写 false
      // "fs": false,
    }
  },
  plugins: [
    // ProvidePlugin 会在模块中自动注入变量,例如 Buffer, process
    new webpack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
      process: 'process/browser',
    }),
  ]
};

要点解释

  • resolve.fallback 会告诉 webpack 如果某个模块在浏览器环境中被 require('crypto'),就去使用 crypto-browserify 这个包来替代。若设置为 false 则表示不提供 polyfill(直接报错或跳过,取决于代码)。(Stack Overflow)
  • ProvidePlugin 自动在模块中注入 Bufferprocess,避免 ReferenceErrorBuffer 常通过 buffer 包提供。(Viglucci)

5. Vue CLI 项目:在 vue.config.js 中做改动(实战示例)

若你用的是 Vue CLI(vue-cli-service),可在项目根目录添加 vue.config.js 并通过 configureWebpack 修改 webpack 配置。示例如下:

// vue.config.js
const webpack = require('webpack');

module.exports = {
  configureWebpack: {
    resolve: {
      fallback: {
        "buffer": require.resolve("buffer/"),
        "stream": require.resolve("stream-browserify"),
        "crypto": require.resolve("crypto-browserify"),
        "path": require.resolve("path-browserify"),
        "os": require.resolve("os-browserify/browser"),
        "assert": require.resolve("assert/"),
        "util": require.resolve("util/"),
      }
    },
    plugins: [
      new webpack.ProvidePlugin({
        Buffer: ['buffer', 'Buffer'],
        process: 'process/browser',
      }),
    ]
  }
};

然后安装依赖:

npm install --save buffer stream-browserify crypto-browserify path-browserify os-browserify assert util process

重启 npm run servenpm run build。若配置正确,构建阶段的 “BREAKING CHANGE” 报错应该消失。若你希望更快速并且不想一个个手动写 fallback,可以用方案 A 的 node-polyfill-webpack-plugin。(NPM)


6. Vite(Vue 3 + create-vue):如何处理

Vite 使用的是 Rollup/esbuild,不是 webpack;因此上面 webpack 的 resolve.fallback 不适用。针对 Vite,常见做法有两种:

6.1 在入口手动 shim(简单、直接)

main.jsmain.ts 顶部加入:

// main.js
import { Buffer } from 'buffer';
window.Buffer = Buffer;

// 或者
// import process from 'process';
// window.process = process;

并安装 buffer

npm install --save buffer

这常常能解决 Buffer is not defined 或需要 process 的情况。(GitHub)

6.2 使用 Rollup 插件 / community polyfills(更完整)

  • rollup-plugin-node-polyfills:为 Rollup 提供 Node 核心模块 polyfills(可集成进 Vite 的 build.rollupOptions.plugins)。
  • vite-plugin-node-polyfills 或其它社区插件:直接注入 polyfills 或全局变量。

示例(概念):

// vite.config.js
import { defineConfig } from 'vite';
import rollupNodePolyFill from 'rollup-plugin-node-polyfills';

export default defineConfig({
  plugins: [],
  resolve: {
    alias: {
      // 某些情况下需要手动 alias
    }
  },
  build: {
    rollupOptions: {
      plugins: [
        rollupNodePolyFill()
      ]
    }
  }
});

建议:如果只需解决 Bufferprocess,入口处手动 shim 足够且包体积小;若项目依赖大量 Node API(例如 crypto、stream),考虑完整的 polyfill 插件或改用对浏览器友好的库。(GitHub)


7. 常见模块与对应浏览器替代包(一览表)

下表给出常见 Node core module 与常用 browser polyfill 包(便于 resolve.fallback 填写):

  • bufferbuffer/ (并用 ProvidePlugin 注入 Buffer). (Viglucci)
  • streamstream-browserify. (Gist)
  • cryptocrypto-browserify. (Gist)
  • pathpath-browserify. (Gist)
  • osos-browserify/browser. (Gist)
  • assertassert/. (Gist)
  • utilutil/. (Gist)
  • processprocess/browser. (Stack Overflow)

安装推荐(一次性):

npm install --save buffer stream-browserify crypto-browserify path-browserify os-browserify assert util process

8. 调试与验证(如何确认生效)

  1. 清理缓存并重建rm -rf node_modules/.cache(或直接删除 node_modulesnpm install),然后 npm run build / npm run serve
  2. 查看构建日志:若之前报错是缺少 crypto / Buffer,修好后这些错误不应再出现。
  3. 在浏览器控制台运行检查

    • 打开开发者工具控制台,输入 typeof Buffer,应返回 "function""object"(表示已注入)。
    • 输入 typeof processprocess.version(注意:在浏览器中 process.version 可能不同,但 typeof process 不应是 undefined)。
  4. Bundle 分析工具:用 webpack-bundle-analyzer 或 Vite 的 build.sourcemapvisualizer 插件查看 polyfill 是否被打包入最终产物(确认是否有意外体积飙升)。(webpack)

9. 性能与包体积注意事项

  • polyfill 会增加产物体积。尤其是 crypto-browserifystream-browserify 等会带入大量代码。生产环境建议仅 polyfill 必需的模块,避免一键把所有 Node API 都带进来。(Gist)
  • 如果某些 Node 模块实际上在浏览器端并不需要(例如 fs, child_process),应在 resolve.fallback 里写 false,并在代码或第三方库中避免使用这些模块。
  • 优先替换依赖:若第三方库只在 Node 环境使用某些功能,考虑寻找或替换为专门为浏览器实现的库(例如使用 Web Crypto API 替代某些 crypto 功能)。
  • 使用 ProvidePlugin(只为 Bufferprocess 之类的全局变量注入)比把大量 polyfill 注入模块作用域更节省,但仍需谨慎。(Viglucci)

10. 真实案例与常见陷阱(FAQ)

Q1:我在 Vue CLI 项目看到错误,但并未直接 require('crypto'),为什么?
A:通常是某个第三方库(如 web3、google-spreadsheet、ethereumjs、某些 SDK)在其内部使用了 Node API。你可以用 npm ls <pkg> 或逐步注释依赖排查,或查看构建日志中报错的模块链路找到来源。(GitHub)

Q2:我用的是 Vite,按 webpack 的方法写 resolve.fallback 没有效果。
A:Vite 使用 Rollup/esbuild,webpack 的 fallback 不适用;用入口 shim(import { Buffer } from 'buffer')或 Rollup 插件来解决。(GitHub)

Q3:为什么 Buffer 注入后仍报错?
A:可能是注入方式错了或在某些模块加载顺序上失效。使用 ProvidePlugin(webpack)或在应用入口处 window.Buffer = Buffer(Vite)通常可靠。确保 buffer 包已正确安装。(Viglucci)

Q4:我不想引入全部 polyfill,有办法只加我需要的吗?
A:可以在 resolve.fallback 中只列出确实需要的模块,并将不需要的模块设为 false。也可以逐个安装替代包并测试。(Stack Overflow)

Q5:有没有官方推荐的“一键”清单?
A:webpack 团队在官方文档 resolve 与配置项中说明如何自定义模块解析;而社区提供了 node-polyfill-webpack-plugin 可以一键注册常见 polyfills(但会带来更多代码)。两者可按需权衡。(webpack)


11. 总结与推荐(我的操作建议)

  • 若你需要 最快速 的修复(开发环境、调试或临时解决):先安装并使用 node-polyfill-webpack-plugin。(NPM)
  • 若你关注 生产体积与可控性:手动 resolve.fallback + ProvidePlugin,只 polyfill 必需模块,其他设为 false。(Stack Overflow)
  • 对于 Vite:优先在入口做 shim(window.Buffer = Bufferimport process from 'process'; window.process = process),只有在确实需要大量 Node API 时再引入 rollup 插件。(GitHub)
  • 若第三方库是罪魁祸首(例如大量 web3、google-spreadsheet 等服务端导向的库),考虑替换为浏览器友好的替代项或在构建时只打包客户端所需部分(tree-shaking / 动态 import)。(GitHub)

附录 A:快速复制的解决步骤(Vue CLI + webpack5)

  1. 安装依赖:
npm install --save buffer stream-browserify crypto-browserify path-browserify os-browserify assert util process
npm install --save-dev node-polyfill-webpack-plugin   # 可选:一键方案
  1. vue.config.js(推荐先试一键方案,如需精细控制改为下面的 manual 配置):

一键插件(最简单)

// vue.config.js
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');

module.exports = {
  configureWebpack: {
    plugins: [
      new NodePolyfillPlugin()
    ]
  }
};

手动方式(更可控)

// vue.config.js
const webpack = require('webpack');

module.exports = {
  configureWebpack: {
    resolve: {
      fallback: {
        "buffer": require.resolve("buffer/"),
        "stream": require.resolve("stream-browserify"),
        "crypto": require.resolve("crypto-browserify"),
        "path": require.resolve("path-browserify"),
        "os": require.resolve("os-browserify/browser"),
        "assert": require.resolve("assert/"),
        "util": require.resolve("util/"),
      }
    },
    plugins: [
      new webpack.ProvidePlugin({
        Buffer: ['buffer', 'Buffer'],
        process: 'process/browser',
      }),
    ]
  }
};
  1. 重启服务并验证(控制台 typeof Buffer / typeof process)。

附录 B:常用参考(可点开阅读)

  • webpack resolve 配置说明(官方文档)。(webpack)
  • StackOverflow:如何在 webpack 5 中 polyfill Node core modules(详解 & 示例)。(Stack Overflow)
  • node-polyfill-webpack-plugin(npm 包说明)。(NPM)
  • Webpack 5 polyfills cheat sheet(哪些包对应哪个 core module)。(Gist)
  • 面向 create-react-app / webpack5 的实战教程(步骤详解)。(Alchemy)

报错解释:

ApiError(406, 'Content-Type header [application/vnd.elasticsearch+json; com] is not supported') 表示客户端发送的请求中的 Content-Type 头部不被服务器支持。HTTP 406 错误表示服务器无法根据客户端请求的内容特性处理请求。

解决方法:

  1. 检查客户端请求的 Content-Type 头部是否正确。对于Elasticsearch,通常正确的 Content-Typeapplication/json
  2. 确保 Content-Type 头部没有额外的参数或者不正确的格式。如果有额里的参数,可能需要移除或者更正。
  3. 如果你正在使用Elasticsearch的特定内容类型 application/vnd.elasticsearch+json,确保没有额外的逗号或分号,并且格式正确。

示例修正请求的代码(如果是使用curl的命令行示例):




curl -X POST "http://example.com:9200/index/_doc/1" -H 'Content-Type: application/json' -d'
{
  "json": "data"
}'

确保在发送请求前修正 Content-Type 头部。如果问题依然存在,请检查Elasticsearch服务器端是否支持该 Content-Type 或者有无其他配置限制。




// 引入ESLint API
const { Linter } = require("eslint");
 
// 使用ESLint API来检查配置
async function inspectConfig(configName) {
  try {
    const linter = new Linter();
    const config = await linter.loadConfig(configName);
    console.log("配置已检查,详情如下:");
    console.dir(config, { depth: null });
  } catch (error) {
    console.error("无法检查配置:", error);
  }
}
 
// 示例:检查.eslintrc.json文件的配置
inspectConfig(".eslintrc.json");

这段代码使用了ESLint的API来加载和检查配置文件,并打印出配置的详细信息。如果配置无法加载,它会捕获错误并打印错误信息。这是一个简单的示例,展示了如何利用ESLint API来进行配置的检查。

在Vue 3项目中,.eslintrc.cjs 是 ESLint 的配置文件,用于定义代码风格和错误检查规则。以下是一些常见的 ESLint 规则及其说明:

  1. "semi": 是否要求在语句末尾使用分号。
  2. "quotes": 指定使用双引号还是单引号。
  3. "comma-dangle": 是否允许对象或数组的尾部有逗号。
  4. "arrow-parens": 是否要求箭头函数的箭头后面总是使用括号。
  5. "vue/multi-word-component-names": 在 Vue 中,组件名是否应该使用多个单词。
  6. "vue/attribute-hyphenation": 在 Vue 中,组件的 props 是否应该使用短横线命名。
  7. "vue/require-default-prop": 是否要求组件的 props 定义默认值。
  8. "vue/require-prop-types": 是否要求组件的 props 定义类型。
  9. "vue/order-in-components": 在 Vue 组件中,定义的组件选项是否应遵循特定顺序。

示例配置:




module.exports = {
  rules: {
    semi: ['error', 'never'],
    quotes: ['error', 'single'],
    'comma-dangle': ['error', 'never'],
    'arrow-parens': ['error', 'as-needed'],
    'vue/multi-word-component-names': 'off',
    'vue/attribute-hyphenation': 'off',
    'vue/require-default-prop': 'warn',
    'vue/require-prop-types': 'off',
    'vue/order-in-components': [
      'error',
      {
        order: [
          'el',
          'name',
          'key',
          'parent',
          'functional',
          ['delimiters', 'comments'],
          ['components', 'directives', 'filters'],
          'extends',
          'mixins',
          'inheritAttrs',
          'model',
          ['props', 'propsData'],
          'computed',
          'methods',
          ['data', 'watch', 'observedData'],
          'LIFECYCLE_HOOKS',
          'template',
          'render',
          'renderError'
        ]
      }
    ]
  }
};

这个配置关闭了一些 Vue 特定的规则,并且设置了其他规则的严格程度。在实际项目中,你可以根据自己的代码风格和团队规范来调整这些规则。

报错解释:

这个错误表明在使用CommonJS模块系统时,react包中缺少一个重要的文件./jsx-runtime.js的引用。JSX是React中的一个扩展语法,它允许我们在JavaScript文件中编写HTML-like的代码。jsx-runtime.js提供了运行时支持,使得我们可以使用不包含运行时的react包,而只使用编译时的转换工具来转换JSX代码。

解决方法:

  1. 确认react包是否正确安装。如果没有安装或安装不完整,可以通过npm或yarn重新安装:

    
    
    
    npm install react

    或者

    
    
    
    yarn add react
  2. 确认项目的依赖版本是否兼容。有时候,依赖库的更新可能会导致不兼容的问题,可以尝试将react包降级到一个稳定且兼容的版本。
  3. 如果你正在使用某种构建工具(如Webpack、Rollup等),确保配置正确,以便它能正确处理JSX文件。
  4. 如果问题依然存在,可以尝试清除缓存(例如使用npm cache clean或者删除node_modulespackage-lock.jsonyarn.lock文件后重新安装依赖)。
  5. 查看项目的package.json文件,确认是否有任何配置错误或者脚本错误导致了这个问题。

如果以上步骤都不能解决问题,可以考虑在项目的issue跟踪器中查找或提问,寻求官方的帮助,因为有时候这可能是一个库级别的问题。




import React from 'react';
import { render } from 'react-dom';
import { connect } from 'dva';
import { Button, Input } from 'antd';
 
// 定义组件
class App extends React.Component {
  handleSubmit = () => {
    const { dispatch, inputValue } = this.props;
    if (inputValue) {
      dispatch({
        type: 'example/submitItem',
        payload: inputValue,
      });
    }
  };
 
  handleInputChange = (e) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'example/changeInputValue',
      payload: e.target.value,
    });
  };
 
  render() {
    const { inputValue } = this.props;
    return (
      <div>
        <Input
          value={inputValue}
          onChange={this.handleInputChange}
          placeholder="请输入内容"
        />
        <Button onClick={this.handleSubmit}>提交</Button>
      </div>
    );
  }
}
 
// 连接dva
const AppContainer = connect(({ example }) => ({
  inputValue: example.inputValue,
}))(App);
 
// 启动应用
render(<AppContainer />, document.getElementById('root'));

这个示例展示了如何使用 Dva.js 管理状态,并通过 React 组件进行展示。它包括了如何定义组件、如何编写事件处理函数以及如何使用 Dva 的 connect 方法将组件连接到应用状态。最后,它通过 react-domrender 方法将应用渲染到页面上的某个元素中。




// 引入JSI相关的API
import {
  NativeModules,
  Platform,
  requireNativeComponent,
} from 'react-native';
 
// 定义JSI相关的模块
export const {MyJSIModule} = NativeModules;
 
// 定义JSI相关的组件
export const MyJSIComponent = requireNativeComponent('MyJSIComponent');
 
// 定义JSI相关的函数
export function myJSIFunction() {
  // 调用JSI模块的方法
  return MyJSIModule.myJSIMethod();
}
 
// 使用示例
import { myJSIFunction } from './path/to/jsi/module';
 
const result = myJSIFunction();
console.log(result);

这个代码示例展示了如何在React Native应用中引入和使用JSI模块。首先,我们通过NativeModulesrequireNativeComponent从原生端引入了JSI模块和组件。然后,我们定义了一个函数myJSIFunction来封装对JSI模块方法的调用。最后,我们展示了如何在应用程序的其他部分调用这个函数并获取结果。这个过程展示了如何在React Native应用中集成和使用JSI技术。

React Native Node是一个React Native项目,它允许开发者在移动应用中运行Node.js。这个项目旨在为开发者提供一个方便的环境,以便他们可以在不离开JavaScript环境的情况下使用Node.js。

以下是如何使用React Native Node的基本步骤:

  1. 克隆项目到本地:



git clone https://github.com/alinz/react-native-node.git
cd react-native-node
  1. 安装依赖:



yarn install
  1. 启动React Native Packager:



yarn start
  1. 在模拟器或真实设备上运行应用:



yarn run:android # 对于 Android
yarn run:ios # 对于 iOS

一旦应用启动,你将看到一个包含Node.js的终端界面,你可以在这里运行Node.js代码。

注意:React Native Node项目可能会随着时间而发展变化,因此在使用时请确保查看最新的项目文档。




// 安装React Native Express和Mongoose依赖
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
 
// 创建Express应用
const app = express();
 
// 使用cors中间件来允许跨源请求
app.use(cors());
 
// 使用body-parser中间件来解析JSON和urlencoded数据
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
 
// 连接到MongoDB数据库
mongoose.connect('mongodb://localhost:27017/rnapp', { useNewUrlParser: true });
 
// 创建一个Schema
const UserSchema = new mongoose.Schema({
  name: String,
  username: String,
  password: String
});
 
// 创建模型
const User = mongoose.model('User', UserSchema);
 
// 创建一个新用户
app.post('/register', (req, res) => {
  const newUser = new User({
    name: req.body.name,
    username: req.body.username,
    password: req.body.password
  });
 
  newUser.save((err) => {
    if (err) {
      res.send('There was a problem adding the information to the database.');
    } else {
      res.send('User added successfully.');
    }
  });
});
 
// 启动Express应用
app.listen(3000, () => {
  console.log('Server running on port 3000');
});

这段代码演示了如何在Express应用中设置一个简单的REST API,用于将用户信息保存到MongoDB数据库。它包括了数据库连接、模型定义、路由处理以及跨源资源共享的配置。这为开发者提供了一个实践的示例,展示了如何将这些技术组合在一起来构建一个可扩展的应用程序。

react-native-render-html 是一个用于 React Native 应用程序的库,它可以解析 HTML 内容并将其渲染为可嵌入组件。以下是如何使用该库的基本示例:

首先,你需要安装这个库:




npm install react-native-render-html

然后,你可以在你的 React Native 应用程序中这样使用它:




import React from 'react';
import { View, Text } from 'react-native';
import HTML from 'react-native-render-html';
 
const App = () => (
  <View style={{ padding: 10 }}>
    <HTML
      html="<h1>Hello, World!</h1><p>This is a <b>simple</b> paragraph.</p>"
    />
  </View>
);
 
export default App;

在这个例子中,HTML 组件接收一个 html 属性,你可以将任何 HTML 字符串赋值给它,并且这个组件会处理解析和渲染的细节。这个库支持许多常见的 HTML 标签和样式,并且通过其文档可以进一步自定义行为。