我嘗試編寫一個公共元件 rd-component
,其中包含一些跨所有專案使用的公共頁面。當我匯入此公共頁面時,顯示錯誤:
Module parse failed: The keyword 'interface' is reserved (15:0)
我做了一個最小的重現範例,這是使用公共頁面的簡單元件:
import './App.css'; import React from 'react'; import Goods from "rd-component/src/component/good/Goods"; const Chat: React.FC = (props) => { return (<Goods></Goods>); } export default Chat;
這是 Index.tsx
:
import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import './index.css'; import reportWebVitals from './reportWebVitals'; import Chat from './App'; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); root.render( <React.StrictMode> <Chat /> </React.StrictMode> ); reportWebVitals();
這是我的 package.json 包含所有套件:
{ "name": "react-demo", "version": "0.1.0", "private": true, "config-overrides-path": "src/config/config-overrides.js", "dependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "@textea/json-viewer": "^2.16.2", "@types/jest": "^27.5.2", "@types/node": "^16.18.21", "@types/react": "^18.0.30", "@types/react-dom": "^18.0.11", "antd": "^5.4.0", "prismjs": "^1.29.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "5.0.1", "react-syntax-highlighter": "^15.5.0", "typescript": "^4.9.5", "web-vitals": "^2.1.4", "rd-component": "0.1.1" }, "scripts": { "start": "react-app-rewired start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "@types/react-syntax-highlighter": "^15.5.6", "customize-cra": "^1.0.0", "react-app-rewired": "^2.2.1" } }
這是執行指令 npm run build
時的完整錯誤輸出:
> react-demo@0.1.0 build > react-scripts build Creating an optimized production build... Failed to compile. Module parse failed: The keyword 'interface' is reserved (15:0) File was processed with these loaders: * ./node_modules/source-map-loader/dist/cjs.js You may need an additional loader to handle the result of these loaders. | import { doPay } from "@/service/pay/PayService"; | > interface IGoodsProp { | appId: string; | }
P粉0314920812024-03-22 13:46:49
預設情況下,TypeScript(或者可能是 create-react-app,如果您正在使用的話)不會從 node_modules
編譯模組。
您的 Goods
元件似乎就是這種情況:
import Goods from "rd-component/src/component/good/Goods";
{
"dependencies": {
// ...
"rd-component": "0.1.1"
}
}
預設配置假設 node_modules
中的所有內容都已準備好供純 JavaScript 專案使用。
因此,TypeScript 編寫的函式庫元件預計已轉換為 JavaScript。
話雖這麼說,您仍然可以嘗試一種簡單的解決方法,其中包括在項目 src
中添加一個指向庫源的 TypeScript 文件的符號鏈接。
IIRC,不幸的是,某些建置引擎「太」智能,甚至可以透過符號連結查看實際路徑...在這種情況下,您必須手動將庫包含在編譯範圍中。
當然,正確的解決方案是預先編譯您的函式庫。