Skip to content

Commit ba14886

Browse files
committed
fix: 服务端支持处理图片等静态资源
1 parent 6f1c03f commit ba14886

File tree

6 files changed

+42
-30
lines changed

6 files changed

+42
-30
lines changed

.eslintrc.json

+1
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@
189189
"ignoreStateless": true
190190
}
191191
],
192+
"react/sort-comp": "off",
192193
"react/no-this-in-sfc": "error",
193194
"react/no-unsafe": [
194195
"error",

build/server/webpack.server.config.js

+22-9
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,27 @@ module.exports = {
4343
]
4444
},
4545
{
46-
test: /.(png|jpg|gif)$/,
47-
use: {
48-
loader: 'file-loader',
49-
options: {
50-
emitFile: false,
51-
name: isProd ? 'img/[name].[hash:8].[ext]' : 'img/[name].[ext]',
52-
publicPath: isProd ? '/' : `http://${__LOCAL_IP__}:${proConfig.wdsPort}`
53-
}
46+
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
47+
loader: 'url-loader',
48+
options: {
49+
limit: 10000,
50+
name: utils.assetsPath('img/[name].[hash:7].[ext]')
51+
}
52+
},
53+
{
54+
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
55+
loader: 'url-loader',
56+
options: {
57+
limit: 10000,
58+
name: utils.assetsPath('media/[name].[hash:7].[ext]')
59+
}
60+
},
61+
{
62+
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
63+
loader: 'url-loader',
64+
options: {
65+
limit: 10000,
66+
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
5467
}
5568
}
5669
]
@@ -64,7 +77,7 @@ module.exports = {
6477
new WebpackBar({
6578
name: 'server',
6679
color: 'orange'
67-
}),
80+
})
6881
],
6982
resolve: {
7083
extensions: ['.js', '.ts', '.tsx', '.json'],

src/client/components/container/index.tsx

+13-15
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ let self: any = null
55

66
const popStateCallback = () => {
77
// 使用popStateFn保存函数防止addEventListener重复注册
8-
if (self && self.getInitialProps) {
9-
self.getInitialProps()
8+
if (self && self.asyncData) {
9+
self.asyncData()
1010
}
1111
}
1212

@@ -29,20 +29,18 @@ interface IState {
2929
export default (SourceComponent: any) =>
3030
class HoComponent extends React.PureComponent<IProps, IState> {
3131
state = {
32-
initialData: {},
33-
canClientFetch: false, // 浏览器端是否需要请求数据
3432
page: {
3533
title: '',
3634
keywords: '',
3735
description: ''
38-
}
36+
},
37+
initialData: {},
38+
canClientFetch: false // 浏览器端是否需要请求数据
3939
}
4040

4141
// 转接子组件的预取方法,服务端会调用这个方法来做数据预取
42-
static async getInitialProps(ctx: any) {
43-
return SourceComponent.getInitialProps
44-
? await SourceComponent.getInitialProps(ctx)
45-
: {}
42+
static async asyncData(ctx: any) {
43+
return SourceComponent.asyncData ? await SourceComponent.asyncData(ctx) : {}
4644
}
4745

4846
async componentDidMount() {
@@ -53,18 +51,18 @@ export default (SourceComponent: any) =>
5351
const canClientFetch = history && history.action === 'PUSH' // 路由跳转的时候可以异步请求数据
5452
if (canClientFetch) {
5553
// 如果是 history PUSH 操作 则更新数据
56-
await this.getInitialProps()
54+
await this.asyncData()
5755
}
5856
}
5957

60-
// 约定所有页面组件内的数据预取方法为getInitialProps,用于双端调用
61-
async getInitialProps() {
62-
// ssr首次进入页面以及csr/ssr切换路由时才调用组件的getInitialProps方法
58+
// 约定所有页面组件内的数据预取方法为asyncData,用于双端调用
59+
async asyncData() {
60+
// ssr首次进入页面以及csr/ssr切换路由时才调用组件的asyncData方法
6361
const store = window.__STORE__ // 从全局得到 store
6462
// 兼容不使用 redux 的页面
6563
// 通过props.getInitialData判断
66-
const res = SourceComponent.getInitialProps
67-
? await SourceComponent.getInitialProps({ store })
64+
const res = SourceComponent.asyncData
65+
? await SourceComponent.asyncData({ store })
6866
: {}
6967
// 处理页面 title 显示
7068
const { tdk } = res.page || {}

src/client/modules/home/index.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ export const Home = () => {
4747
}
4848
// ! 约定 服务端会调用这个方法 ===> 相当于是生命周期
4949
// 这一块可能会设计到把redux的操作
50-
Home.getInitialProps = ({ store }: any) => {
50+
Home.asyncData = ({ store }: any) => {
5151
// TODO 在这个生命周期调用getInitialData
5252
store.dispatch.home.getInitialData()
5353
}

src/server/middlewares/genHtml.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export default async function genHtml(
2929
let fetchDataFn
3030
let fetchResult = {}
3131
if (targetRoute) {
32-
fetchDataFn = targetRoute.component ? targetRoute.component.getInitialProps : null
32+
fetchDataFn = targetRoute.component ? targetRoute.component.asyncData : null
3333
if (fetchDataFn) {
3434
// 更新 state
3535
fetchResult = await fetchDataFn({ store })

tests/components/container.spec.jsx

+4-4
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ describe('test AsyncBundle component', () => {
2626
const nameElement = screen.getByText('vnues')
2727
expect(nameElement.tagName).toBe('P')
2828
})
29-
it('should return the correct default when client render call getInitialProps', async () => {
29+
it('should return the correct default when client render call asyncData', async () => {
3030
// 前端模拟webpack替换_SERVER__
3131
window.__SERVER__ = null
3232
function SourceComponent(props) {
@@ -41,7 +41,7 @@ describe('test AsyncBundle component', () => {
4141
)
4242
}
4343
const user = { name: 'Tom', age: 24 }
44-
SourceComponent.getInitialProps = async function () {
44+
SourceComponent.asyncData = async function () {
4545
function getUser() {
4646
return new Promise(resolve => {
4747
setTimeout(() => {
@@ -67,15 +67,15 @@ describe('test AsyncBundle component', () => {
6767
action: 'PUSH'
6868
}
6969
render(<ContainerComponent history={history} />)
70-
const { data } = await ContainerComponent.getInitialProps()
70+
const { data } = await ContainerComponent.asyncData()
7171
expect(data).toEqual(user)
7272
expect(await screen.findByText('Tom')).toBeInTheDocument()
7373
expect(await screen.findByText('24')).toBeInTheDocument()
7474
// 放在这里执行 有了await回调的效果
7575
expect(document.title).toBe('首页')
7676
})
7777

78-
it('should return the correct default when server render call getInitialProps', async () => {
78+
it('should return the correct default when server render call asyncData', async () => {
7979
// 前端模拟webpack替换_SERVER__
8080
window.__SERVER__ = {}
8181
function SourceComponent(props) {

0 commit comments

Comments
 (0)