ant-design / ant-design-mobile

Essential UI blocks for building mobile web apps.
https://mobile.ant.design
MIT License
11.66k stars 2.4k forks source link

服务端渲染报错 #4254

Closed childrentime closed 3 years ago

childrentime commented 3 years ago

环境版本说明: os: win10 node: v14.17.5 antd-mobile: ^5.0.0-beta.15 @loadable/component: ^5.15.0 @loadable/server: ^5.15.1

app.tsx `import { Switch, Route } from 'react-router-dom'; import loadable from '@loadable/component'; import './main.css';

const Index = loadable(() => import('./pages/index')); const Announcement = loadable(() => import('./pages/announcement')); const Me = loadable(() => import('./pages/me')); const Faq = loadable(() => import('./pages/faq')); const Mainsite = loadable(() => import('./pages/mainsite')); const AnswerEditor = loadable(() => import('./components/answer/editor')); const Search = loadable(() => import('./pages/search')); const SearchResult = loadable(() => import('./pages/searchResult')); const QuestionEditor = loadable(() => import('./components/question/editor'));

function App() { return (

);

} export default App; `

src/index.tsx `import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import App from './app'; import { loadableReady } from '@loadable/component';

loadableReady(() => ReactDOM.hydrate(

, document.getElementById('root') ) ).then(() => console.log('loaded'));` server/index.ts `import path from 'path'; import Koa from 'koa'; import router from './route'; import serve from 'koa-static'; import proxy from 'koa2-proxy-middleware'; const app = new Koa(); /*静态资源访问 访问client打包之后的js文件*/ const main = serve(path.resolve('dist')); app.use(main); // 后台请求转发 const options = { targets: { '/api/(.*)': { target: 'http://forum-api.kdocs.cn/', changeOrigin: true } } }; app.use(proxy(options)); app.use(router.routes()); app.listen(3002, () => { console.log('服务端渲染 run in port 3002'); }); ` server/route.tsx `import { Context } from 'koa'; import Router from 'koa-router'; import React from 'react'; import { StaticRouter } from 'react-router-dom'; import { renderToString } from 'react-dom/server'; import App from '../src/App'; import { ChunkExtractor } from '@loadable/server'; import path from 'path'; import { enableStaticRendering } from 'mobx-react-lite'; enableStaticRendering(true); const router = new Router(); //对于所有的路由 我们都返回这个 //只有手动刷新的时候 才会执行这个方法 //否则是 客户端的 broswerRouter接管路由 router.get('(.*)', async (ctx: Context) => { console.log(ctx.request.url); // This is the stats file generated by webpack loadable plugin const statsFile = path.resolve('dist/loadable-stats.json'); // We create an extractor from the statsFile const extractor = new ChunkExtractor({ statsFile, entrypoints: ['index'] }); // Wrap your application using "collectChunks" const jsx = extractor.collectChunks( ); // Render your application const html = renderToString(jsx); // You can now collect your script tags const scriptTags = extractor.getScriptTags(); // or extractor.getScriptElements(); // You can also collect your "preload/prefetch" links const linkTags = extractor.getLinkTags(); ctx.response.body = ` ${linkTags}
${html}
${scriptTags} `; }); export default router;` webpack.client.ts `import { CleanWebpackPlugin } from 'clean-webpack-plugin'; import path from 'path'; import HtmlWebpackPlugin from 'html-webpack-plugin'; const LoadablePlugin = require('@loadable/webpack-plugin'); //客户端打包 module.exports = { mode: 'production', entry: { index: path.join(__dirname, '../src/index.tsx') }, output: { filename: '[name].[contenthash].js', publicPath: '/', path: path.resolve(__dirname, '../dist') }, resolve: { alias: { '@': path.resolve(__dirname, '../src') }, extensions: ['.ts', '.tsx', '.js', '.json'] }, module: { rules: [ //babel 配置 { test: /\.tsx?$/, use: { loader: 'babel-loader', options: { presets: [ '@babel/preset-env', [ '@babel/preset-react', { runtime: 'automatic' } ], '@babel/preset-typescript' ], plugins: [ [ '@babel/plugin-transform-runtime', { corejs: 3 } ], ['@babel/plugin-syntax-dynamic-import'], ['@loadable/babel-plugin'] ] } }, exclude: /node_modules/ //排除 node_modules 目录 }, //图片 { test: /\.(png|jpg|gif|svg|svg+xml)$/i, type: 'asset/inline' }, { test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/inline' }, //css配置 { test: /\.css$/i, use: ['style-loader', 'css-loader'] }, //less { test: /\.less$/i, use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'less-loader', options: { lessOptions: { strictMath: true } } } ] } ] }, plugins: [ new CleanWebpackPlugin(), new LoadablePlugin(), new HtmlWebpackPlugin({ template: 'public/index.html', filename: path.resolve('index.html'), chunk: ['index'] }) ] }; ` webpack.server.ts `import { CleanWebpackPlugin } from 'clean-webpack-plugin'; import path from 'path'; import nodeExternals from 'webpack-node-externals'; const noRequireCss = require('./purge-css'); module.exports = { mode: 'production', entry: { index: path.join(__dirname, '../server/index.ts') }, externalsPresets: { node: true }, //相当于 target:node externals: [nodeExternals()], output: { filename: 'bundle.js', publicPath: '', path: path.resolve(__dirname, '../target'), globalObject: `typeof self !== 'undefined' ? self : this` }, resolve: { alias: { '@': path.resolve(__dirname, '../src') }, extensions: ['.ts', '.tsx', '.js', '.json'] }, module: { rules: [ //babel 配置 { test: /\.tsx?$/, use: { loader: 'babel-loader', options: { presets: [ '@babel/preset-env', [ '@babel/preset-react', { runtime: 'automatic' } ], '@babel/preset-typescript' ], plugins: [ [ '@babel/plugin-transform-runtime', { corejs: 3 } ], [noRequireCss], ['dynamic-import-node'], ['@loadable/babel-plugin'] ] } }, exclude: /node_modules/ //排除 node_modules 目录 } ] }, plugins: [new CleanWebpackPlugin()] };` 运行 node/target.js 报错信息 服务端渲染 run in port 3002 / loadable-components: failed to synchronously load component, which expected to be available { fileName: 8050, chunkName: 'pages-index', error: "Unexpected token ':'" } C:\Users\wps\Desktop\Jingying\forum\node_modules\antd-mobile\cjs\global\global.css:1 :root { ^ SyntaxError: Unexpected token ':' at wrapSafe (internal/modules/cjs/loader.js:988:16) at Module._compile (internal/modules/cjs/loader.js:1036:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10) at Module.load (internal/modules/cjs/loader.js:937:32) at Function.Module._load (internal/modules/cjs/loader.js:778:12) at Module.require (internal/modules/cjs/loader.js:961:19) at require (internal/modules/cjs/helpers.js:92:18) at Object. (C:\Users\wps\Desktop\Jingying\forum\node_modules\antd-mobile\cjs\global\index.js:3:1) at Module._compile (internal/modules/cjs/loader.js:1072:14) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
childrentime commented 3 years ago

格式不太好 我重新提一个