[英]TypeScript 2.8: preact and react in one compilation
根據下面的網站,我認為我可以在一個編譯中使用preact並做出反應。 但是,當我試圖一次使用這些庫時,就會發生沖突。 我認為preact and react仍然具有全局JSX名稱空間,因此暫時不能混用。 如果我的配置錯誤,請告訴我。
JSX是通過JSX工廠解析的。當前,當TypeScript使用JSX時,它將查找全局JSX命名空間以查找某些類型(例如,“ JSX組件的類型是什么?”)。 在TypeScript 2.8中,編譯器將嘗試根據JSX工廠的位置查找JSX名稱空間。 例如,如果您的JSX工廠是React.createElement,TypeScript將嘗試首先解析React.JSX,然后從當前范圍內解析JSX。
當混合和匹配不同的庫(例如React和Preact)或特定庫的不同版本(例如React 14和React 16)時,這會很有幫助,因為將JSX名稱空間放在全局范圍內可能會引起問題。
import {h, Component} from 'preact';
export interface HelloWorldProps {
name: string
}
export default class PreactUserComp extends Component<HelloWorldProps, any>
{
render (props: HelloWorldProps) {
return <h1>Hello {props.name}!</h1>
}
}
最初的第一行是/ ** @jsx h * /。 但是該編輯器無法將其識別為正確的代碼。
import * as React from "react";
export interface HelloProps { firstName: string; lastName: string; }
interface Person {
firstName: string;
lastName: string;
}
class User implements Person {
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
function formatName(user:User): string {
return user.firstName + ' ' + user.lastName;
}
export class ReactUserComp extends React.Component<HelloProps, {}> {
render() {
return <h1>Hello {this.props.firstName} {this.props.lastName}!</h1>;
}
}
import { h, render } from 'preact';
import PreactUserComp from './components/PreactUser';
render(<PreactUserComp name="Preact" />, document.querySelector('#app'));
{
"name": "typescript-preact-react",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/react": "^16.3.13",
"@types/react-dom": "^16.0.5",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"preact": "^8.2.7",
"ts-loader": "^4.2.0",
"typescript": "^2.8.3",
"webpack": "^4.6.0"
},
"devDependencies": {
"typescript": "^2.8.3",
"webpack": "^4.6.0",
"webpack-cli": "^2.0.15"
}
}
{
"compilerOptions": {
"sourceMap": true,
"module": "commonjs",
"jsx": "react",
"target": "es5"
},
"include": [
"src/*.ts",
"src/*.tsx"
]
}
var path = require('path');
module.exports = {
devtool: 'source-map',
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js'
},
resolve: {
extensions: ['.ts', '.tsx']
},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
loaders: ['ts-loader']
}
]
}
}
<div id =“ app”> </ div> <script src =“ dist / app.js”> </ script>
最初index.html包含的代碼很少,但是此編輯器無法將其識別為正確的代碼,因此我對代碼進行了總結。
這確實是問題所在。 為了使用React
以及Preact
使用typescript
,你需要有自己的聲明文件( typings.d.ts
)。
我不完全知道應該怎么做的細節。 但是我想要為我的項目進行類似的設置,並找到了一個試圖解決此問題的Github項目。
鏈接: Hotell / react-preact-typescript-interop
我還沒有嘗試過。 但是我認為這會在一定程度上幫助您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.