我试着写了一个公共组件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();
这是我的包裹。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;
| }
2条答案
按热度按时间nnt7mjpx1#
默认情况下,TypeScript(或者可能是create-react-app,如果你正在使用的话)不会编译
node_modules
中的模块。你的
Goods
组件似乎就是这种情况:默认配置假设
node_modules
中的所有内容都准备好供普通JavaScript项目使用。因此,TypeScript编写的库组件应该已经被编译成JavaScript。
话虽如此,您仍然可以尝试一个简单的解决方法,即在项目
src
中设置一个指向库源代码的TypeScript文件的符号链接。不幸的是,有些构建引擎“太”聪明了,甚至通过符号链接也能看到实际的路径。..在这种情况下,您必须手动将库包含在编译范围中。
当然,正确的解决方案是预编译库。
p8ekf7hl2#
问题是
react-scripts
加载webpack时没有正确的Typescript加载器。解决这个问题最简单的方法是在react项目中添加一个
tsconfig.json
文件。如果公共组件在
node_modules
文件夹中,无论是通过使用工作区还是npm包,您都必须使用npm run eject
弹出项目,并编辑生成的config/webpack.config.js
,以包括使用typescript处理node_modules,这有点复杂,因为您必须搜索isTypescript()
,以及后面的对象。删除exclude
和include
属性。