Closed
Description
구글북스에서 구매 후 보고 있습니다.
20.3.5 정적 파일 제공하기
index.server.js의 createPage함수
-
manifest[...]
부분manifest.files[...]
로 해야 정상 작동합니다. -
하이픈이 아니라 물결표로 되어있습니다.
manifest['runtime~main.js']
->manifest['runtime-main.js']
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import express from 'express';
import { StaticRouter } from 'react-router-dom';
import App from './App';
import path from 'path';
import fs from 'fs';
const manifest = JSON.parse(
fs.readFileSync(path.resolve('./build/asset-manifest.json'), 'utf8')
);
const chunks = Object.keys(manifest.files)
.filter(key => /chunk\.js$/.exec(key))
// -------------------------------↓↓-------------------------------
.map(key => `<script src="https://github.com/$%7Bmanifest[key]%7D"></script>`)
//-----------------------------------------------------------------
.join('');
function createPage(root) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="shortcut icon" href="https://github.com/favicon.ico"/>
<meta name="theme-color" content="#000000" />
<title>React App</title>
// ---------------- ↓↓ ----------------------------------------------
<link href="https://github.com/$%7Bmanifest['main.css']}" rel="stylesheet" />
//--------------------------------------------------------------------
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root">
${root}
</div>
// ------------------↓↓-----------↓ --------------------------------
<script src="https://github.com/$%7Bmanifest['runtime-main.js']}"></script>
//--------------------------------------------------------------------
${chunks}
// ----------------- ↓↓ ----------------------------------------------
<script src="https://github.com/$%7Bmanifest['main.js']}"></script>
//--------------------------------------------------------------------
</body>
</html>
`;
}
const app = express();
const serverRender = (req, res, next) => {
const context = {};
const jsx = (
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
);
const root = ReactDOMServer.renderToString(jsx);
res.send(createPage(root));
};
const serve = express.static(path.resolve('./build'), {
index: false,
});
app.use(serve);
app.use(serverRender);
app.listen(5000, () => {
console.log('Running on http://localhost:5000');
});
제가 초보라서 잘못하거나 실수한 것 일 수도 있으니 확인 한번 부탁드리겠습니다!!
Metadata
Metadata
Assignees
Labels
No labels