React新手求助:Vite构建Atlaskit Editor页面空白及报错问题
Vite+React+TS集成Atlaskit Editor页面空白且报错
项目配置与代码详情
package.json
{ "name": "atlaskit-editor", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc && vite build", "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview" }, "dependencies": { "react": "^18.2.0", "react-dom": "^18.2.0", "@atlaskit/editor-core": "^185.8.0" }, "devDependencies": { "@types/react": "^18.0.37", "@types/react-dom": "^18.0.11", "@typescript-eslint/eslint-plugin": "^5.59.0", "@typescript-eslint/parser": "^5.59.0", "@vitejs/plugin-react": "^4.0.0", "eslint": "^8.38.0", "eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-refresh": "^0.3.4", "typescript": "^5.0.2", "vite": "^4.3.9" } }
App.tsx
import { Editor } from "@atlaskit/editor-core"; import "./App.css"; function App() { return ( <> <div> <Editor /> </div> </> ); } export default App;
Main.tsx
import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App.tsx"; import "./index.css"; ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( <React.StrictMode> <App /> </React.StrictMode> );
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React + TS</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html>
报错信息
控制台提示process is not defined,原因是Atlaskit Editor依赖Node.js环境中的process变量,但Vite默认在浏览器环境中不提供该变量,导致组件初始化失败,页面空白。
解决步骤
- 安装polyfill依赖
在终端执行命令:
npm install @esbuild-plugins/node-globals-polyfill @esbuild-plugins/node-modules-polyfill --save-dev
- 配置Vite
在项目根目录创建vite.config.ts文件,添加以下内容:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'; import { NodeModulesPolyfillPlugin } from '@esbuild-plugins/node-modules-polyfill'; export default defineConfig({ plugins: [react()], optimizeDeps: { esbuildOptions: { plugins: [ NodeGlobalsPolyfillPlugin({ process: true, buffer: true }), NodeModulesPolyfillPlugin() ] } }, resolve: { alias: { process: 'process/browser', buffer: 'buffer' } } });
- 优化容器样式
在App.css中给Editor容器设置高度,确保组件正常显示:
div { height: 500px; }
- 重启服务
停止当前开发服务器,重新执行npm run dev,即可看到Atlaskit Editor正常渲染。
内容的提问来源于stack exchange,提问作者Mr.Price
相关产品推荐
相关产品推荐

