Skip to content

Commit 1ec98e6

Browse files
authored
feat: add dva example (#46)
1 parent b2fbfd1 commit 1ec98e6

35 files changed

+13230
-0
lines changed

example/ssr-with-dva/.gitignore

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Logs
2+
logs
3+
*.log
4+
npm-debug.log*
5+
yarn-debug.log*
6+
yarn-error.log*
7+
8+
# Runtime data
9+
pids
10+
*.pid
11+
*.seed
12+
*.pid.lock
13+
14+
# Directory for instrumented libs generated by jscoverage/JSCover
15+
lib-cov
16+
17+
# Coverage directory used by tools like istanbul
18+
coverage
19+
20+
# nyc test coverage
21+
.nyc_output
22+
23+
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24+
.grunt
25+
26+
# Bower dependency directory (https://bower.io/)
27+
bower_components
28+
29+
# node-waf configuration
30+
.lock-wscript
31+
32+
# Compiled binary addons (https://nodejs.org/api/addons.html)
33+
build/Release
34+
35+
# Dependency directories
36+
node_modules/
37+
jspm_packages/
38+
39+
# TypeScript v1 declaration files
40+
typings/
41+
42+
# Optional npm cache directory
43+
.npm
44+
45+
# Optional eslint cache
46+
.eslintcache
47+
48+
# Optional REPL history
49+
.node_repl_history
50+
51+
# Output of 'npm pack'
52+
*.tgz
53+
54+
# Yarn Integrity file
55+
.yarn-integrity
56+
57+
# dotenv environment variables file
58+
.env
59+
60+
# next.js build output
61+
.next
62+
63+
.DS_Store
64+
65+
.vscode
66+
67+
run/
68+
69+
dist/
70+
71+
package-lock.json

example/ssr-with-dva/README.md

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Egg + React + SSR应用骨架
2+
3+
详细用法实现请查看[官方文档](http://ykfe.net)
4+
5+
# Getting Start
6+
7+
这里我们提供了一个脚手架来方便你创建项目
8+
9+
```
10+
$ npm install yk-cli -g
11+
$ ykcli init <Your Project Name>
12+
$ cd <Your Project Name>
13+
$ npm i
14+
$ npm start
15+
$ open http://localhost:7001
16+
```
17+
18+
# 功能/特性
19+
20+
- [x] 基于cra脚手架开发,由cra开发的React App可无缝迁移,如果你熟悉cra的配置,上手成本几乎为0
21+
- [x] 小而美,相比于beidou,next.js这样的高度封装方案,我们的实现原理和开发模式一目了然
22+
- [x] 同时支持SSR以及CSR两种开发模式,本地开发环境以及线上环境皆可无缝切换两种渲染模式
23+
- [x] 统一前端路由与服务端路由,无需重复编写路由文件配置
24+
- [x] 支持切换路由时自动获取数据
25+
- [x] 支持本地开发HMR
26+
- [x] 稳定性经过线上大规模应用验证,可提供性能优化方案
27+
- [x] 支持tree shaking以及打包去重依赖,使得打包的bundle非常小,为同样复杂度的next.js项目的0.4倍
28+
- [x] 支持csr/ssr自定义layout,无需通过path来手动区分
29+
- [ ] 配套[TypeScript](https://github.com/ykfe/egg-react-ssr-typescript)版本的实现
30+
- [ ] 配套serverless版本的实现
31+
32+
33+

example/ssr-with-dva/app.js

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2+
module.exports = app => {
3+
4+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
const Controller = require('egg').Controller
3+
const { renderToStream } = require('ykfe-utils')
4+
5+
class PageController extends Controller {
6+
async index () {
7+
const { ctx } = this
8+
try {
9+
// Page为webpack打包的chunkName,项目默认的entry为Page
10+
ctx.type = 'text/html'
11+
ctx.status = 200
12+
const stream = await renderToStream(ctx, 'Page', ctx.app.config)
13+
ctx.body = stream
14+
} catch (error) {
15+
ctx.logger.error(`Page Controller renderToStream Error ${error}`)
16+
}
17+
}
18+
}
19+
20+
module.exports = PageController

example/ssr-with-dva/app/router.js

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
'use strict'
2+
3+
module.exports = app => {
4+
const { router, controller } = app
5+
app.config.routes.map(route => {
6+
router.get(`${route.path}`, controller[route.controller][route.handler])
7+
})
8+
}

example/ssr-with-dva/build/env.js

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
'use strict'
2+
3+
const fs = require('fs')
4+
const path = require('path')
5+
const paths = require('./paths')
6+
7+
// Make sure that including paths.js after env.js will read .env variables.
8+
delete require.cache[require.resolve('./paths')]
9+
10+
const NODE_ENV = process.env.NODE_ENV
11+
if (!NODE_ENV) {
12+
throw new Error(
13+
'The NODE_ENV environment variable is required but was not specified.'
14+
)
15+
}
16+
17+
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
18+
var dotenvFiles = [
19+
`${paths.dotenv}.${NODE_ENV}.local`,
20+
`${paths.dotenv}.${NODE_ENV}`,
21+
// Don't include `.env.local` for `test` environment
22+
// since normally you expect tests to produce the same
23+
// results for everyone
24+
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
25+
paths.dotenv
26+
].filter(Boolean)
27+
28+
// Load environment variables from .env* files. Suppress warnings using silent
29+
// if this file is missing. dotenv will never modify any environment variables
30+
// that have already been set. Variable expansion is supported in .env files.
31+
// https://github.com/motdotla/dotenv
32+
// https://github.com/motdotla/dotenv-expand
33+
dotenvFiles.forEach(dotenvFile => {
34+
if (fs.existsSync(dotenvFile)) {
35+
require('dotenv-expand')(
36+
require('dotenv').config({
37+
path: dotenvFile
38+
})
39+
)
40+
}
41+
})
42+
43+
// We support resolving modules according to `NODE_PATH`.
44+
// This lets you use absolute paths in imports inside large monorepos:
45+
// https://github.com/facebook/create-react-app/issues/253.
46+
// It works similar to `NODE_PATH` in Node itself:
47+
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
48+
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
49+
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
50+
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
51+
// We also resolve them to make sure all tools using them work consistently.
52+
const appDirectory = fs.realpathSync(process.cwd())
53+
process.env.NODE_PATH = (process.env.NODE_PATH || '')
54+
.split(path.delimiter)
55+
.filter(folder => folder && !path.isAbsolute(folder))
56+
.map(folder => path.resolve(appDirectory, folder))
57+
.join(path.delimiter)
58+
59+
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
60+
// injected into the application via DefinePlugin in Webpack configuration.
61+
const REACT_APP = /^REACT_APP_/i
62+
63+
function getClientEnvironment (publicUrl) {
64+
const raw = Object.keys(process.env)
65+
.filter(key => REACT_APP.test(key))
66+
.reduce(
67+
(env, key) => {
68+
env[key] = process.env[key]
69+
return env
70+
},
71+
{
72+
// Useful for determining whether we’re running in production mode.
73+
// Most importantly, it switches React into the correct mode.
74+
NODE_ENV: process.env.NODE_ENV || 'development',
75+
// Useful for resolving the correct path to static assets in `public`.
76+
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
77+
// This should only be used as an escape hatch. Normally you would put
78+
// images into the `src` and `import` them in code to get their paths.
79+
PUBLIC_URL: publicUrl
80+
}
81+
)
82+
// Stringify all values so we can feed into Webpack DefinePlugin
83+
const stringified = {
84+
'process.env': Object.keys(raw).reduce((env, key) => {
85+
env[key] = JSON.stringify(raw[key])
86+
return env
87+
}, {})
88+
}
89+
90+
return { raw, stringified }
91+
}
92+
93+
module.exports = getClientEnvironment
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
'use strict'
2+
3+
// This is a custom Jest transformer turning style imports into empty objects.
4+
// http://facebook.github.io/jest/docs/en/webpack.html
5+
6+
module.exports = {
7+
process () {
8+
return 'module.exports = {};'
9+
},
10+
getCacheKey () {
11+
// The output is always the same.
12+
return 'cssTransform'
13+
}
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'use strict'
2+
3+
const path = require('path')
4+
5+
// This is a custom Jest transformer turning file imports into filenames.
6+
// http://facebook.github.io/jest/docs/en/webpack.html
7+
8+
module.exports = {
9+
process (src, filename) {
10+
const assetFilename = JSON.stringify(path.basename(filename))
11+
12+
if (filename.match(/\.svg$/)) {
13+
return `module.exports = {
14+
__esModule: true,
15+
default: ${assetFilename},
16+
ReactComponent: (props) => ({
17+
$$typeof: Symbol.for('react.element'),
18+
type: 'svg',
19+
ref: null,
20+
key: null,
21+
props: Object.assign({}, props, {
22+
children: ${assetFilename}
23+
})
24+
}),
25+
};`
26+
}
27+
28+
return `module.exports = ${assetFilename};`
29+
}
30+
}

example/ssr-with-dva/build/paths.js

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
'use strict'
2+
3+
const path = require('path')
4+
const fs = require('fs')
5+
const url = require('url')
6+
7+
// Make sure any symlinks in the project folder are resolved:
8+
// https://github.com/facebook/create-react-app/issues/637
9+
const appDirectory = fs.realpathSync(process.cwd())
10+
const resolveApp = relativePath => path.resolve(appDirectory, relativePath)
11+
12+
const envPublicUrl = process.env.PUBLIC_URL
13+
14+
function ensureSlash (inputPath, needsSlash) {
15+
const hasSlash = inputPath.endsWith('/')
16+
if (hasSlash && !needsSlash) {
17+
return inputPath.substr(0, inputPath.length - 1)
18+
} else if (!hasSlash && needsSlash) {
19+
return `${inputPath}/`
20+
} else {
21+
return inputPath
22+
}
23+
}
24+
25+
const getPublicUrl = appPackageJson =>
26+
envPublicUrl || require(appPackageJson).homepage
27+
28+
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
29+
// "public path" at which the app is served.
30+
// Webpack needs to know it to put the right <script> hrefs into HTML even in
31+
// single-page apps that may serve index.html for nested URLs like /todos/42.
32+
// We can't use a relative path in HTML because we don't want to load something
33+
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
34+
function getServedPath (appPackageJson) {
35+
const publicUrl = getPublicUrl(appPackageJson)
36+
const servedUrl =
37+
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/')
38+
return ensureSlash(servedUrl, true)
39+
}
40+
41+
const moduleFileExtensions = [
42+
'web.mjs',
43+
'mjs',
44+
'web.js',
45+
'js',
46+
'web.ts',
47+
'ts',
48+
'web.tsx',
49+
'tsx',
50+
'json',
51+
'web.jsx',
52+
'jsx'
53+
]
54+
55+
// config after eject: we're in ./config/
56+
module.exports = {
57+
dotenv: resolveApp('.env'),
58+
appPath: resolveApp('.'),
59+
appBuild: resolveApp('dist'),
60+
appPublic: resolveApp('app/public'),
61+
appPackageJson: resolveApp('package.json'),
62+
appSrc: resolveApp('web'),
63+
entry: resolveApp('web/entry'),
64+
appNodeModules: resolveApp('node_modules'),
65+
publicUrl: getPublicUrl(resolveApp('package.json')),
66+
servedPath: getServedPath(resolveApp('package.json')),
67+
template: resolveApp('web/index.html'),
68+
resolveApp: resolveApp
69+
}
70+
71+
module.exports.moduleFileExtensions = moduleFileExtensions

0 commit comments

Comments
 (0)