Skip to content

Commit 1cde877

Browse files
committed
fix: 优化构建
1 parent c94ca14 commit 1cde877

File tree

19 files changed

+152
-50
lines changed

19 files changed

+152
-50
lines changed

.circleci/config.yml

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ jobs:
3535
name: Avoid hosts unknown for github
3636
command: mkdir ~/.ssh/ && echo -e "Host github.com\n\tStrictHostKeyChecking no\n" > ~/.ssh/config
3737
- run: npm run docs:build
38+
- run: npm run build
3839
- run: ls -al
3940
- run: # git push
4041
name: push-github

build/client/utils.js

-5
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
const path = require('path')
22
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
33

4-
const theme = path.join(__dirname, '../../src/client/style/antd.override.theme.less')
5-
64
const config = require('../../config')
75

86
exports.resolve = function (dir) {
@@ -50,9 +48,6 @@ exports.styleLoaders = function (options) {
5048
{
5149
loader: 'less-loader',
5250
options: {
53-
modifyconsts: {
54-
hack: `true; @import "${theme}";` // Override with less file
55-
},
5651
javascriptEnabled: true
5752
}
5853
}

build/client/webpack.base.conf.js

-8
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
const path = require('path')
2-
const HtmlWebpackPlugin = require('html-webpack-plugin')
32
const WebpackBar = require('webpackbar')
43
const webpack = require('webpack')
54
const ESLintPlugin = require('eslint-webpack-plugin')
65
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin')
76
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
8-
97
const utils = require('./utils')
108
const config = require('../../config')
119

@@ -80,12 +78,6 @@ module.exports = {
8078
name: 'client',
8179
color: 'green'
8280
}),
83-
new HtmlWebpackPlugin({
84-
title: config.base.title,
85-
filename: 'index.html',
86-
template: path.resolve(__dirname, '../../templates/index.ejs'),
87-
inject: true
88-
}),
8981
new webpack.DefinePlugin({
9082
'process.env': JSON.stringify({ NODE_ENV: 'development' }),
9183
__IS_PROD__: false,

build/client/webpack.dev.conf.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
const path = require('path')
12
const webpack = require('webpack')
23
const { merge } = require('webpack-merge')
34
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
45
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
5-
6+
const HtmlWebpackPlugin = require('html-webpack-plugin')
67
const baseWebpackConfig = require('./webpack.base.conf')
8+
const config = require('../../config')
79

810
module.exports = merge(baseWebpackConfig, {
911
mode: 'development',
@@ -35,6 +37,12 @@ module.exports = merge(baseWebpackConfig, {
3537
},
3638
devtool: 'cheap-source-map',
3739
plugins: [
40+
new HtmlWebpackPlugin({
41+
title: config.base.title,
42+
filename: 'index.html',
43+
template: path.resolve(__dirname, '../../templates/index.ejs'),
44+
inject: true
45+
}),
3846
new FriendlyErrorsWebpackPlugin(),
3947
new webpack.HotModuleReplacementPlugin(),
4048
new BundleAnalyzerPlugin.BundleAnalyzerPlugin({

build/client/webpack.prod.conf.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,12 @@ module.exports = merge(baseWebpackConfig, {
4949
}
5050
}),
5151
new TerserPlugin({
52-
parallel: true
52+
parallel: true,
53+
compress: {
54+
drop_console: true,
55+
drop_debugger: false,
56+
pure_funcs: ['console.log'] // 移除console
57+
}
5358
}),
5459
new CompressionWebpackPlugin({
5560
compressionOptions: {

build/server/utils.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const path = require('path')
2+
3+
const config = require('../../config')
4+
exports.resolve = function (dir) {
5+
return path.join(__dirname, '../../', dir)
6+
}
7+
8+
exports.assetsPath = function (_path) {
9+
// assetsSubDirectory ==> assets目录
10+
const assetsSubDirectory = config.base.assetsSubDirectory
11+
return path.posix.join('../static', assetsSubDirectory, _path)
12+
}

build/server/webpack.server.config.js

+4-10
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ const path = require('path')
22
const nodeExternals = require('webpack-node-externals')
33
const webpack = require('webpack')
44
const resolvePath = pathstr => path.resolve(__dirname, pathstr)
5-
var utils = require('../client/utils')
5+
var utils = require('./utils')
66
process.env.BABEL_ENV = 'node' // 设置 babel 的运行环境
77
const proConfig = require('../../config/pro-config')
88
const WebpackBar = require('webpackbar')
@@ -47,29 +47,23 @@ module.exports = {
4747
loader: 'url-loader',
4848
options: {
4949
limit: 10000,
50-
name: isProd
51-
? utils.assetsPath('staic/img/[name].[hash:7].[ext]')
52-
: utils.assetsPath('img/[name].[hash:7].[ext]')
50+
name: utils.assetsPath('img/[name].[hash:7].[ext]')
5351
}
5452
},
5553
{
5654
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
5755
loader: 'url-loader',
5856
options: {
5957
limit: 10000,
60-
name: isProd
61-
? utils.assetsPath('static/media/[name].[hash:7].[ext]')
62-
: utils.assetsPath('media/[name].[hash:7].[ext]')
58+
name: utils.assetsPath('media/[name].[hash:7].[ext]')
6359
}
6460
},
6561
{
6662
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
6763
loader: 'url-loader',
6864
options: {
6965
limit: 10000,
70-
name: isProd
71-
? utils.assetsPath('static/fonts/[name].[hash:7].[ext]')
72-
: utils.assetsPath('fonts/[name].[hash:7].[ext]')
66+
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
7367
}
7468
}
7569
]

config/base.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@ module.exports = {
44
title: 'noov.js',
55
projectName: 'static',
66
assetsPublicPath: 'http://localhost:8080/', // 涉及到热更新的host jsonp客户端的地址
7-
assetsSubDirectory: 'static',
7+
assetsSubDirectory: 'assets',
88
assetsRoot: path.resolve(__dirname, '../dist')
99
}

package.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"dev": "npm run client:dev & node ./dist/server/app",
1515
"client:dev": "node ./build/client/dev-server.js",
1616
"server:dev": "node ./build/server/dev-server.js",
17-
"build": "npm run client:build && npm run server:build",
17+
"build": "rimraf './dist' & npm run client:build && npm run server:build",
1818
"client:build": "node ./build/client/prod-build.js",
1919
"server:build": "cross-env NODE_ENV=production webpack --config ./build/server/webpack.server.config.js",
2020
"server-dev:build": "cross-env NODE_ENV=development node ./build/server/dev-build.js",
@@ -42,6 +42,7 @@
4242
"history": "^5.0.0",
4343
"isomorphic-style-loader": "^5.1.0",
4444
"koa": "^2.13.1",
45+
"koa-send": "^5.0.0",
4546
"koa-static": "^5.0.0",
4647
"koa2-proxy-middleware": "0.0.4",
4748
"react": "^17.0.2",
@@ -122,6 +123,7 @@
122123
"prettier": "^2.2.1",
123124
"redux-devtools-extension": "^2.13.9",
124125
"redux-logger": "^3.0.6",
126+
"rimraf": "^2.7.1",
125127
"standard-version": "^9.2.0",
126128
"style-loader": "^2.0.0",
127129
"stylelint": "^13.13.0",

src/client/components/container/index.tsx

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const popStateCallback = () => {
1010
}
1111
}
1212

13-
interface ITdk {
13+
export interface ITdk {
1414
title: string
1515
keywords: string
1616
description: string
@@ -70,7 +70,7 @@ export default (SourceComponent: any) =>
7070
document.title = tdk.title
7171
}
7272
this.setState({
73-
initialData: res,
73+
initialData: res.data,
7474
page: res.page,
7575
canClientFetch: true
7676
})

src/client/modules/home/index.tsx

+10-2
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ export const Home = (props: any) => {
4444
onClick={handleClick}
4545
onKeyDown={handleClick}
4646
>
47-
点一点
47+
点一点1
4848
</div>
4949
<span className="button--green click-btn">作者:{name}</span>
5050
<span className="button--green click-btn">ID:{id}</span>
@@ -58,12 +58,20 @@ Home.asyncData = ({ store }: any) => {
5858
name: 'vnues',
5959
id: '@1213'
6060
}
61+
const page = {
62+
title: '首页',
63+
keywords: 'noov.js',
64+
description: 'react-ssr解决方案'
65+
}
6166
// TODO 这里改动 服务端没有做更新
6267
// 在异步请求更新store 我们建议放在action操作 应该少一个textarea资源
6368
store.dispatch.home.setUser(data)
6469
return new Promise(resolve => {
6570
setTimeout(() => {
66-
resolve(data)
71+
resolve({
72+
data,
73+
page
74+
})
6775
}, 2000)
6876
})
6977
}

src/config/tdk.ts

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export default {
2+
'/': {
3+
title: 'home',
4+
keywords: 'noov.js',
5+
description: '一套react-ssr解决方案'
6+
}
7+
}

src/server/app/index.ts

+4-6
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import Koa from 'koa'
2-
import koaStatic from 'koa-static'
2+
import koaStatic from '../middlewares/koa-static'
33
import proxy from 'koa2-proxy-middleware'
44
import ssrMiddleware from '../middlewares/ssr'
55
import proConfig from '../../../config/pro-config'
6+
import path from 'path'
67

78
const port = proConfig.nodeServerPort || process.env.PORT
89

@@ -27,15 +28,12 @@ if (process.env.NODE_ENV === 'development') {
2728
app.use(proxy(options))
2829
}
2930

30-
console.log('__dirname', __dirname)
31-
32-
console.log('koaStatic', koaStatic)
33-
app.use(koaStatic('./static'))
31+
app.use(koaStatic(path.join(__dirname, '../static'), { prefix: '/static' }))
3432

3533
// ssr 中间件
3634
app.use(ssrMiddleware)
3735

3836
// 启动服务
39-
app.listen(3000, () => {
37+
app.listen(port, () => {
4038
console.log('server is start .', `http://localhost:${port}`)
4139
})

src/server/middlewares/koa-static.ts

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* Module dependencies.
3+
*/
4+
import Koa from 'koa'
5+
import { resolve } from 'path'
6+
import assert from 'assert'
7+
import send from 'koa-send'
8+
9+
/**
10+
* Serve static files from `root`.
11+
*
12+
* @param {String} root
13+
* @param {Object} [opts]
14+
* @return {Function}
15+
* @api public
16+
*/
17+
18+
function serve(root: string, opts: any) {
19+
opts = { ...opts }
20+
21+
assert(root, 'root directory is required to serve files')
22+
23+
// options
24+
opts.root = resolve(root)
25+
if (opts.index !== false) opts.index = opts.index || 'index.html'
26+
27+
if (!opts.defer) {
28+
return async function serve(ctx: Koa.Context, next: Koa.Next) {
29+
let done = false
30+
31+
if (ctx.method === 'HEAD' || ctx.method === 'GET') {
32+
if (opts.prefix && ctx.path.indexOf(opts.prefix) === 0) {
33+
ctx.path = ctx.path.slice(opts.prefix.length)
34+
}
35+
36+
try {
37+
done = ((await send(ctx, ctx.path, opts)) as unknown) as boolean
38+
} catch (err) {
39+
if (err.status !== 404) {
40+
throw err
41+
}
42+
}
43+
}
44+
45+
if (!done) {
46+
await next()
47+
}
48+
}
49+
}
50+
51+
return async function serve(ctx: Koa.Context, next: Koa.Next) {
52+
await next()
53+
54+
if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return
55+
// response is already handled
56+
if (ctx.body != null || ctx.status !== 404) return // eslint-disable-line
57+
58+
try {
59+
await send(ctx, ctx.path, opts)
60+
} catch (err) {
61+
if (err.status !== 404) {
62+
throw err
63+
}
64+
}
65+
}
66+
}
67+
68+
export default serve

src/server/middlewares/ssr.ts

+5-11
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import fs from 'fs'
66
import path from 'path'
77
import genHtml from './genHtml'
88
import Koa from 'koa'
9+
import tdkConfig from '../../config/tdk'
910

1011
const ejsPath = path.join(__dirname, '../../templates/server.ejs')
1112
const store = getStore()
@@ -21,14 +22,10 @@ export default async (ctx: Koa.Context, next: Koa.Next): Promise<null> => {
2122
styles.forEach((style: any) => cssObj.add(style._getContent()))
2223
const { html, fetchResult } = await genHtml(path, insertCss, store)
2324
const { page } = fetchResult || {}
24-
let tdk = {
25-
title: 'noov.js',
26-
keywords: '默认关键词',
27-
description: '默认描述'
28-
}
25+
let tdk = tdkConfig[path as keyof typeof tdkConfig]
2926
// 添加TDK
30-
if (page && page.tdk) {
31-
tdk = page.tdk
27+
if (Object.keys(page).length) {
28+
tdk = page
3229
}
3330
const styles: string[] = []
3431
Array.from(cssObj).forEach((item: any) => {
@@ -43,7 +40,6 @@ export default async (ctx: Koa.Context, next: Koa.Next): Promise<null> => {
4340
js: [],
4441
css: []
4542
}
46-
console.log('assets===>', assets)
4743
if (typeof (assets as Promise<IAssets>).then === 'function') {
4844
const res = await (assets as Promise<IAssets>)
4945
assetsMap = res as typeof assetsMap
@@ -53,7 +49,6 @@ export default async (ctx: Koa.Context, next: Koa.Next): Promise<null> => {
5349
return assetsMap
5450
}
5551
const assetsMap = await getAssetsMap()
56-
console.log('assetsMap', assetsMap)
5752
const template = fs.readFileSync(ejsPath, { encoding: 'utf-8' })
5853
const result = ejs.render(template, {
5954
tdk,
@@ -66,8 +61,7 @@ export default async (ctx: Koa.Context, next: Koa.Next): Promise<null> => {
6661
showInitData: Object.keys(fetchResult || {}).length > 0,
6762
showState: Object.keys(store.getState() || {}).length > 0
6863
})
69-
console.log('result', result)
7064
ctx.body = result
71-
await next()
65+
// await next()
7266
return null
7367
}

src/server/utils/assets.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export default function getAssets(): IAssets | Promise<IAssets> {
2020
// 生产环境 从 asset-manifest.json 读取资源
2121
const map = res.default
2222
Object.keys(map).forEach(item => {
23-
if (item.indexOf('.js') > -1) {
23+
if (/.+\.js$/.test(item)) {
2424
assets.js.push(`<script type="text/javascript" src="${map[item]}"></script>`)
2525
}
2626
})

0 commit comments

Comments
 (0)