Skip to content

Commit c0b33ca

Browse files
committed
feat: 迁移到ts
1 parent 0e2a98e commit c0b33ca

File tree

19 files changed

+77
-71
lines changed

19 files changed

+77
-71
lines changed

.eslintrc.json

+18-14
Original file line numberDiff line numberDiff line change
@@ -137,20 +137,23 @@
137137
"no-trailing-spaces": "off",
138138
"no-undef-init": "error",
139139
"class-methods-use-this": "off",
140-
"no-underscore-dangle": [
141-
"error",
142-
{
143-
"allow": [
144-
"__INITIAL_DATA__",
145-
"__STORE__",
146-
"_insertCss",
147-
"__SERVER__",
148-
"__IS_PROD__"
149-
],
150-
"allowAfterThis": true,
151-
"allowAfterThisConstructor": true
152-
}
153-
],
140+
// "no-underscore-dangle": [
141+
// "error",
142+
// {
143+
// "allow": [
144+
// "__INITIAL_DATA__",
145+
// "__STORE__",
146+
// "_insertCss",
147+
// "__SERVER__",
148+
// "__IS_PROD__",
149+
// "__IS_SSR__",
150+
// "_getContent"
151+
// ],
152+
// "allowAfterThis": true,
153+
// "allowAfterThisConstructor": true
154+
// }
155+
// ],
156+
"no-underscore-dangle": "off",
154157
"no-unsafe-finally": "error",
155158
"no-unused-expressions": [
156159
"error",
@@ -182,6 +185,7 @@
182185
"no-restricted-syntax": "off",
183186
"import/extensions": "off",
184187
"import/no-unresolved": "off",
188+
"import/no-mutable-exports": "off",
185189
"react/no-unused-state": "error",
186190
"react/self-closing-comp": "error",
187191
"react/boolean-prop-naming": ["error", { "rule": "^(is|has)[A-Z]([A-Za-z0-9]?)+" }],

.npmrc

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
registry=https://registry.npm.taobao.org
1+
# registry=https://registry.npm.taobao.org

build/server/dev-server.js

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
// 开发环境 node 服务启动入口
22
const getPort = require('./free-port')
33
const localIp = process.argv[process.argv.length - 1] // 获得 本机ip 地址
4-
const proConfig = require('../../src/common/pro-config')
5-
6-
global.__LOCAL__IP__=localIp
4+
const proConfig = require('../../config/pro-config')
75

6+
global.__LOCAL__IP__ = localIp
87

98
// node server port
109
const nodeServerPort = proConfig.nodeServerPort
1110

12-
1311
//启动前检查端口是否占用,杀掉占用端口的进程
1412
getPort(nodeServerPort)
1513

build/server/webpack.server.config.js

+2-7
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@ var utils = require('../client/utils')
99
//构建前清理目录
1010
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
1111
process.env.BABEL_ENV = 'node' //设置 babel 的运行环境
12-
const proConfig = require('../../src/common/pro-config')
12+
const proConfig = require('../../config/pro-config')
1313

1414
const isProd = process.env.NODE_ENV === 'production'
1515

1616
module.exports = {
1717
mode: process.env.NODE_ENV,
1818
target: 'node',
19-
entry: resolvePath('../../src/server/app/index.js'), //入口文件
19+
entry: resolvePath('../../src/server/app/index.ts'), //入口文件
2020
output: {
2121
filename: 'app.js',
2222
path: resolvePath('../../dist/server')
@@ -38,11 +38,6 @@ module.exports = {
3838
'less-loader'
3939
]
4040
},
41-
{
42-
test: /\.jsx?$/,
43-
loader: 'babel-loader',
44-
exclude: /node_modules/
45-
},
4641
{
4742
test: /\.ts|\.tsx/,
4843
use: [

build/start.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,14 @@ const startNodeServer = () => {
4646
})
4747
}
4848

49+
let flag = false
4950
// 控制台输出信息
5051
function print(data) {
5152
let str = data.toString()
52-
if (str.indexOf(constantCode.SVRCODECOMPLETED) > -1) {
53+
if (str.indexOf(constantCode.SVRCODECOMPLETED) > -1 && !flag) {
54+
flag = true
5355
// 服务端代码编译完成
56+
console.log('启动服务端')
5457
startNodeServer() // 重启 node 服务
5558
} else {
5659
console.log(str)

package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,15 @@
3434
"koa2-proxy-middleware": "0.0.4",
3535
"react": "^17.0.2",
3636
"react-dom": "^17.0.2",
37+
"react-hot-loader": "^4.13.0",
3738
"react-redux": "^7.2.4",
3839
"react-router-config": "^5.1.1",
3940
"react-router-dom": "^5.2.0",
4041
"redux": "^4.1.0",
4142
"redux-actions": "^2.6.5",
4243
"redux-promise-middleware": "^6.1.2",
4344
"sa-sdk-javascript": "^1.16.12",
44-
"uuid": "^8.3.2",
45-
"react-hot-loader": "^4.13.0"
45+
"uuid": "^8.3.2"
4646
},
4747
"devDependencies": {
4848
"@babel/core": "^7.13.16",

src/client/components/asyncBundle/index.tsx

+3-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import LoadingCompoent from '../loading'
1010

1111
interface IPops {
1212
children: any
13+
load: any
1314
}
1415
export default class AsyncBundle extends React.PureComponent<IPops, any> {
1516
state = {
@@ -18,7 +19,7 @@ export default class AsyncBundle extends React.PureComponent<IPops, any> {
1819

1920
componentDidMount() {
2021
const { mod } = this.state
21-
if (mod) {
22+
if (!mod) {
2223
this.load(this.props)
2324
}
2425
}
@@ -37,6 +38,7 @@ export default class AsyncBundle extends React.PureComponent<IPops, any> {
3738

3839
render() {
3940
const { mod } = this.state
41+
console.log('mod', mod)
4042
const { children } = this.props
4143
return mod ? children(mod) : <LoadingCompoent />
4244
}

src/client/components/asyncLoader/index.tsx

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ import AsyncBundle from '../asyncBundle'
33
import proConfig from '../../../../config/pro-config'
44

55
function AsyncLoader(loader: any) {
6-
function asyncFn(props: any) {
7-
return <AsyncBundle load={loader}>{(Comp: any) => <Comp {...props} />}</AsyncBundle>
8-
}
6+
const asyncFn: any = (props: any) => (
7+
<AsyncBundle load={loader}>{(Comp: any) => <Comp {...props} />}</AsyncBundle>
8+
)
99
// 标记为异步组件
1010
asyncFn[proConfig.asyncComponentKey] = true
1111

src/client/components/container/index.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ export default (SourceComponent: any) =>
6363
const { staticContext } = this.props
6464
const { canClientFetch, initialData } = this.state
6565

66-
if (window.__SERVER__) {
66+
if (__SERVER__) {
6767
// 服务端渲染
6868
props.initialData = staticContext.initialData || {}
6969
} else {

src/client/main/index.tsx

+4
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ function renderDom(routeList: any[], initStoreState?: Store) {
1616
return () => removeCss.forEach(dispose => dispose()) // 组件卸载时 移除当前的 style 标签
1717
}
1818
// !redux数据更新
19+
20+
console.log('initStoreState', initStoreState)
1921
const store = getStore(initStoreState)
2022
// 服务端只需要获取state就行 我们方法的定义在redux就定义好了
2123
console.log('同步更新的客户端store', store.getState())
@@ -56,6 +58,8 @@ function clientRender(routeList: any) {
5658
const { targetRoute } = matchResult
5759
if (targetRoute) {
5860
// 预加载 等待异步脚本加载完成
61+
console.log('proConfig', proConfig)
62+
console.log('targetRoute', targetRoute)
5963
if (targetRoute.component[proConfig.asyncComponentKey]) {
6064
targetRoute
6165
.component()

src/client/main/route-config.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
1-
const routes: any[] = []
2-
1+
let routes: any[] = []
32
try {
43
const context = require.context(`../modules`, true, /.*\/routes\.tsx?$/)
54
context.keys().forEach((key: string) => {
65
const route = context(key).default
7-
routes.push(route)
6+
routes = routes.concat(route)
87
})
98
} catch (err) {
109
console.warn(err.message)
1110
}
1211

1312
console.log('>>> routes: ', JSON.stringify(routes))
14-
1513
export default routes

src/client/main/router.tsx

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { Route, Switch } from 'react-router-dom'
55
const App = ({ routeList }: any) => (
66
<Layout>
77
<Switch>
8+
{console.log('routeList', routeList)}
89
{routeList.map((item: any) => (
910
<Route key={item.path} {...item} />
1011
))}

src/client/modules/home/index.tsx

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@ export const Home = (props: any) => {
1212
<div className="home">
1313
<h1>hello react-ssr</h1>
1414
<button onClick={handleClick}>click me1的顶顶顶顶顶的</button>
15-
{[111, 2, 3, 4, 5, 6111, 17, 338, 1232221].map((item: number) => (
15+
{[111, 22, 44, 55].map((item: number) => (
1616
<div key={item}>{item}</div>
1717
))}
18+
<p>11</p>
1819
<Link to="/history">2222clqick to2 404 page12为</Link>
1920
</div>
2021
)

src/client/modules/home/routes.tsx

+11-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
import * as React from 'react'
2-
import AsyncLoader from '@/components/asyncLoader';
3-
2+
import AsyncLoader from '@/components/asyncLoader'
43

4+
// 这种不能被做到热更新 那么应该reload啊
5+
// todo 这里有bug
56
function pageNotFound({ staticContext }: any) {
67
if (staticContext) {
7-
staticContext.code = 404;
8+
staticContext.code = 404
89
}
910

10-
return <div>404页面</div>
11+
return (
12+
<div>
13+
<p>404页面page22</p>
14+
<p>12</p>
15+
</div>
16+
)
1117
}
1218
export default [
1319
{
@@ -18,6 +24,6 @@ export default [
1824
{
1925
path: '*',
2026
component: pageNotFound,
21-
// exact: true
27+
exact: true
2228
}
2329
]

src/client/store/reducers.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@ import { init } from '@rematch/core'
22
import promise from 'redux-promise-middleware'
33
import home from './home'
44

5-
6-
export default function getStore(initState?:any){
5+
export default function getStore(initState?: any) {
76
const store = init({
87
models: { home },
98
redux: {
10-
initialState:initState,
9+
initialState: initState || {},
1110
reducers: {},
1211
middlewares: [promise]
1312
}

src/common/match-route.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export interface IMatchRoute {
55
targetMatch: any
66
}
77
export default (path: string, routeList: any[]): IMatchRoute => {
8-
let targetRoute = ''
8+
let targetRoute
99
let targetMatch
1010

1111
for (const item of routeList) {

src/server/middlewares/ssr.ts src/server/middlewares/ssr.tsx

+9-15
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,18 @@
11
import React from 'react'
22
import { renderToString } from 'react-dom/server'
3-
import { StaticRouter } from 'react-router'
3+
import { StaticRouter } from 'react-router-dom'
44
import StyleContext from 'isomorphic-style-loader/StyleContext'
55
import { Provider } from 'react-redux'
66
import routeList from '../../client/main/route-config'
77
import matchRoute from '../../common/match-route'
8-
8+
import App from '../../client/main/router'
99
import getStaticRoutes from '../utils/get-static-routes'
10-
1110
import proConfig from '../../../config/pro-config'
12-
1311
import getAssets from '../utils/assets'
14-
// css 同构的上下文
15-
1612
import getStore from '../../client/store/reducers'
1713

1814
const store = getStore()
1915

20-
console.log('store', store)
21-
22-
// 得到 store,默认没有数据
23-
2416
export default async (ctx: any, next: any) => {
2517
const { path } = ctx.request
2618

@@ -33,11 +25,12 @@ export default async (ctx: any, next: any) => {
3325

3426
// 查找到的目标路由对象
3527
const matchResult = await matchRoute(path, staticRoutesList)
36-
const { targetRoute, targetMatch } = matchResult
28+
console.log('matchResult', matchResult)
29+
const { targetRoute } = matchResult
3730

3831
// 进行数据预取,更新 store 内的数据
3932
let fetchDataFn
40-
let fetchResult = {}
33+
let fetchResult: any = {}
4134
if (targetRoute) {
4235
fetchDataFn = targetRoute.component ? targetRoute.component.getInitialProps : null
4336
if (fetchDataFn) {
@@ -67,16 +60,16 @@ export default async (ctx: any, next: any) => {
6760
styles.forEach((style: any) => cssObj.add(style._getContent()))
6861
const html = renderToString(
6962
<Provider store={store}>
70-
<StaticRouter location={path} context={context}>
63+
<StaticRouter location={path} context={context as any}>
7164
<StyleContext.Provider value={{ insertCss }}>
7265
<App routeList={staticRoutesList} />
7366
</StyleContext.Provider>
7467
</StaticRouter>
7568
</Provider>
7669
)
77-
70+
console.log('html', html)
7871
const styles: string[] = []
79-
;[...cssObj].forEach(item => {
72+
Array.from(cssObj).forEach((item: any) => {
8073
const [mid, content] = item[0]
8174
styles.push(`<style id="s${mid}-0">${content}</style>`)
8275
})
@@ -110,4 +103,5 @@ export default async (ctx: any, next: any) => {
110103
${assetsMap.js.join('')}
111104
`
112105
await next()
106+
return null
113107
}

src/server/utils/assets.ts

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import map from '@dist/server/asset-manifest.json'
1+
// import map from '@dist/server/asset-mainfest.json'
22
// 生产环境中 静态资源的处理
33

44
interface IAssets {
@@ -26,14 +26,14 @@ export default function getAssets(): any {
2626
} else {
2727
// 生产环境 从 asset-manifest.json 读取资源
2828
jsFiles.forEach(item => {
29-
if (map[item]) {
30-
assets.js.push(`<script type="text/javascript" src="${map[item]}"></script>`)
31-
}
29+
// if (map[item]) {
30+
// assets.js.push(`<script type="text/javascript" src="${map[item]}"></script>`)
31+
// }
3232
})
3333
cssFiles.forEach(item => {
34-
if (map[item]) {
35-
assets.css.push(`<link rel="stylesheet" type="text/css" href="${map[item]}" />`)
36-
}
34+
// if (map[item]) {
35+
// assets.css.push(`<link rel="stylesheet" type="text/css" href="${map[item]}" />`)
36+
// }
3737
})
3838
}
3939

tsconfig.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
"@library/*": ["src/client/library/*"],
1111
"@modules/*": ["src/client/modules/*"],
1212
"@style/*": ["src/client/style/*"],
13-
"@components/*": ["src/client/components/*"]
13+
"@components/*": ["src/client/components/*"],
14+
"@dist/*": ["dist/*"]
1415
},
1516
"types": ["node", "webpack-env"],
1617
"target": "es5",

0 commit comments

Comments
 (0)