React Server Framework Next.js 블로그를 사용합니다. 마음에 드는 경우 스타 지원을 제공합니다. https://github.com/weibozzz/next-blog 온라인 주소 : http://www.liuweibo.cn이 프로젝트는 다음에 사용합니다. https://github.com/weibozz/weibozz.github.io
소프트웨어 아키텍처 설명 react.js next.js antd mysql node koa2 fetch
구성 폴더 아래에 ENV.JS의 ISSHOW를 입력하여 true로 설정하십시오 . 여기서 나는 단지 내 자신의 온라인 인터페이스를 호출합니다. 물론, 당신은 그것을보고 인터페이스를 수정할 수는 없습니다. False 인 경우 인터페이스를 조정할 수 없으며 인터페이스를 직접 작성해야합니다.
cnpm i
npm run devcnpm i
npm run build
npm start우리는 Next.js의 도움으로 전적으로 개발 된 개인 웹 사이트와 온라인 주소 http://www.liuweibo.cn을 사용하여 완료 후 개발 사용 경험과 경험을 요약합니다. gtihub 소스 코드 https://github.com/weibozzz/next-blog. 당신이 그것을 좋아한다면, 스타를 지원하십시오.
여기서 핵심 사항에 대해 이야기합시다
server.js 여기에서 공식 express 사용하고 동시에 gzip 압축을 활성화하십시오.
const express = require ( 'express' )
const next = require ( 'next' )
const compression = require ( 'compression' )
const dev = process . env . NODE_ENV !== 'production'
const app = next ( { dev } )
const handle = app . getRequestHandler ( )
let port = dev ? 4322 : 80
app . prepare ( )
. then ( ( ) => {
const server = express ( )
if ( ! dev ) {
server . use ( compression ( ) ) //gzip
}
//文章二级页面
server . get ( '/p/:id' , ( req , res ) => {
const actualPage = '/detail'
const queryParams = { id : req . params . id }
app . render ( req , res , actualPage , queryParams )
} )
server . get ( '*' , ( req , res ) => {
return handle ( req , res )
} )
server . listen ( port , ( err ) => {
if ( err ) throw err
console . log ( '> Ready on http://localhost ' port )
} )
} )
. catch ( ( ex ) => {
process . exit ( 1 )
} ) Redux 데이터를 전달하는 데 사용되며 Store는 일반 React 사용과 동일하며 헤더 및 바닥 글을 여기에 배치 할 수 있으며 _err.js 404 페이지를 처리하는 데 사용됩니다.
import App , { Container } from 'next/app'
import React from 'react'
import { withRouter } from 'next/router' // 接入next的router
import withReduxStore from '../lib/with-redux-store' // 接入next的redux
import { Provider } from 'react-redux'
class MyApp extends App {
render ( ) {
const { Component , pageProps , reduxStore , router : { pathname } } = this . props ;
return (
< Container >
< Provider store = { reduxStore } >
< Component { ... myPageProps } />
</ Provider >
</ Container >
)
}
}
export default withReduxStore ( withRouter ( MyApp ) ) link 는 페이지로 점프하고 원래 http : //***.com을 변경하는 데 사용됩니다. ID = 1은 아름다운/id/1으로 변경합니다.head SEO에 대한 메타 태그를 둥지 할 수 있습니다 import dynamic from 'next/dynamic' ;
//不需要seo
const DynasicTopTipsNoSsr = dynamic ( import ( '../../components/TopTips' ) , {
ssr : false
} )
import React , { Component } from 'react'
import { connect } from 'react-redux'
import Router from 'next/router'
import 'whatwg-fetch' // 用于fetch请求数据
import Link from 'next/link' ; // next的跳转link
import Head from 'next/head' // next的跳转head可用于seo
class Blog extends Component {
render ( ) {
return (
< div className = "Blog" >
< Head >
< title > { BLOG_TXT } » { COMMON_TITLE } </ title >
</ Head >
< MyLayout >
< Link as = { `/Blog/ ${ current } ` } href = { `/Blog?id= ${ current } ` } >
< a onClick = { this . onClickPageChange . bind ( this ) } > { current } </ a >
</ Link >
</ MyLayout >
</ div >
)
}
}
//这里才是重点,getInitialProps方法来请求数据进行渲染,达到服务端渲染的目的
Blog . getInitialProps = async function ( context ) {
const { id = 1 } = context . query
let queryStringObj = {
type : ALL ,
num : id ,
pageNum
}
let queryTotalString = { type : ALL } ;
const pageBlog = await fetch ( getBlogUrl ( queryStringObj ) )
const pageBlogData = await pageBlog . json ( )
return { pageBlogData }
}
// 这里根据需要传入redux
const mapStateToProps = state => {
const { res , searchData , searchTotalData } = state
return { res , searchData , searchTotalData } ;
}
export default connect ( mapStateToProps ) ( Blog ) 루트 디렉토리에서 static 폴더를 만듭니다. 이것은 필수 요구 사항입니다. 그렇지 않으면 정적 리소스가로드되지 않습니다.
Antd-Custom
@primary-color : # 722ED0;
@layout-header-height : 40px;
@border-radius-base : 0px;스타일
@import "~antd/dist/antd.less" ;
@import "./antd-custom.less" ; 마지막으로 구성은 공개 head 에서 통합됩니다
< Head >
< meta charSet =" utf-8 " />
< meta httpEquiv =" X-UA-Compatible " content =" IE=edge, chrome=1 " />
< meta name =" viewport "
content =" width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no " />
< meta name =" renderer " content =" webkit " />
< meta httpEquiv =" description " content ="刘伟波-伟波前端" />
< meta name =" author " content ="刘伟波,liuweibo " />
< link rel =' stylesheet ' href =' /_next/static/style.css ' />
< link rel =' stylesheet ' type =' text/css ' href =' /static/nprogress.css ' />
< link rel =' shortcut icon ' type =' image/x-icon ' href =' /static/favicon.ico ' />
</ Head > .babelrc 파일
{
"presets" : [ " next/babel " ],
"plugins" : [
" transform-decorators-legacy " ,
[
" import " ,
{
"libraryName" : " antd " ,
"style" : " less "
}
]
]
}
next.config.js 파일 구성
const withLess = require ( '@zeit/next-less' )
module . exports = withLess (
{
lessLoaderOptions : {
javascriptEnabled : true ,
cssModules : true ,
}
}
) vue 의 scope , style jsx , global Global으로 추가하는 것처럼 느껴집니다. 그렇지 않으면 여기에서만 적용됩니다.
render ( ) {
return (
< Container >
< Provider store = { reduxStore } >
< Component { ... myPageProps } />
</ Provider >
< style jsx global > { `
.fl{
float: left;
}
.fr{
float: right;
}
` } </ style >
</ Container >
) import Router from 'next/router'
import NProgress from 'nprogress'
Router . onRouteChangeStart = ( url ) => {
NProgress . start ( )
}
Router . onRouteChangeComplete = ( ) => NProgress . done ( )
Router . onRouteChangeError = ( ) => NProgress . done ( ) marked('放入markdown字符串');
import marked from 'marked'
import hljs from 'highlight.js' ;
hljs . configure ( {
tabReplace : ' ' ,
classPrefix : 'hljs-' ,
languages : [ 'CSS' , 'HTML, XML' , 'JavaScript' , 'PHP' , 'Python' , 'Stylus' , 'TypeScript' , 'Markdown' ]
} )
marked . setOptions ( {
highlight : ( code ) => hljs . highlightAuto ( code ) . value ,
gfm : true ,
tables : true ,
breaks : false ,
pedantic : false ,
sanitize : true ,
smartLists : true ,
smartypants : false
} ) ; next.config.js 파일 구성
module . exports = {
webpack ( config , ... args ) {
return config ;
}
} config.resolve.alias = {
...config.resolve.alias,
'@': path.resolve(__dirname, './'),
}
config.plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': process.env.NODE_ENV
})
)
config.module.rules.push(
{
test: /.svg(?v=d+.d+.d+)?$/,
use: [
{
loader: 'babel-loader'
},
{
loader: '@svgr/webpack',
options: {
babel: false,
icon: true
}
}
]
}
)
config = withCSS()
.webpack(config, ...args)
config = withLess()
.webpack(config, ...args)
const loaderUtils = require('loader-utils')
const fs = require('fs')
const path = require('path')
const cssModuleRegex = /.module.less$/
config = withLess(
// 开启 css module 自定义
{
cssModules: true,
cssLoaderOptions: {
importLoaders: 1,
minimize: !args[0].dev,
getLocalIdent: (loaderContext, _, localName, options) => {
const fileName = path.basename(loaderContext.resourcePath)
if (cssModuleRegex.test(fileName)) {
const content = fs.readFileSync(loaderContext.resourcePath)
.toString()
const name = fileName.replace(/.[^/.]+$/, '')
const hash = args[0].dev ? `${name}___[hash:base64:5]` : '[hash:base64:5]'
const fileNameHash = loaderUtils.interpolateName(
loaderContext,
hash,
{ content }
)
return fileNameHash
}
return localName
}
}
}
)
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true'
})
config = withBundleAnalyzer({})
.webpack(config, ...args)
))
큰 방문이 있으면 데이터를 캐시해야합니다.
CDN 노드 뷰 이미지 날짜
구성 이미지 설명 및 변경
고품질 사진 업로드는 아직 업로드를 지원하지 않으며 코드 개선 업로드
정확히 1m 버그로 업로드되었습니다
로그인 한 후 좋아하는 기사를 지원하고 주석을 수정하십시오
이전 기사가 삭제되면 자체 증가 ID는 자체 증가하지 않으며 데이터베이스를 쿼리해야합니다.
Nugget과 유사한 Markdown 코드를 강조 표시하기 위해 마크 다운 코드를 작성하십시오.
그날 병합 할 버전
contentEditablegithub : https : //github.com/weibozzz
개인 블로그 : http://www.liuweibo.cn
segmentfault : https : //segmentfault.com/u/weibozzz
공개 플랫폼 : Weibo Frontend
저자 : Liu Weibo
링크 : http://www.liuweibo.cn/p/206
출처 : Liu Weibo의 블로그
이 기사의 원래 저작권은 Liu Weibo에 속합니다. 재 인쇄시 소스를 표시하십시오. 협력 해 주셔서 감사합니다.