react express 服务端渲染 css @import 报错
项目使用webpack的devServer可以正常启动,配置ssr后,css @import 报错
express 配置
import '@babel/polyfill'
import React from 'react';
import {renderToString} from 'react-dom/server';
import Home from './src/component/Home';
import path from 'path';
import express from 'express';
const ROOT_PATH = path.resolve(__dirname);
const BUILD_PATH = path.resolve(ROOT_PATH, 'build');
const app = express();
app.use(express.static(BUILD_PATH));
app.use('*', function (req, res) {
res.write('<!DOCTYPE html><html><head><title>Hello HomePage</title><link href="/static/css/bundle.css" rel="stylesheet"></head><body>');
res.write('<div id="app">');
res.write(renderToString(<Home />));
res.write('</div></body>');
res.write('<script type="text/javascript" src="/static/js/bundle.js"></script>');
res.write('</html>');
});
const server = app.listen(3000, () => {
const host = server.address().address;
const port = server.address().port;
console.log('server is start at', host, port);
});
/*
全局css
@import './iconfont.css';
@import './color.css';
@import './font.css';
@import './margin.css';
@import './size.css';
@import './algin.css';
@import './float.css';
@import './display.css';
#root {
width: 100% !important;
height: 100% !important;
}
使用 babel-node ./express.js
启动,报错
(function (exports, require, module, __filename, __dirname) { @import './iconfont.css';
^
SyntaxError: Invalid or unexpected token
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:657:28)
at Module._extensions..js (internal/modules/cjs/loader.js:700:10)
......
如果不ssr,只是用express启动项目,是没问题的
import path from 'path';
import express from 'express';
const ROOT_PATH = path.resolve(__dirname);
const BUILD_PATH = path.resolve(ROOT_PATH, 'build');
const app = express();
app.use(express.static(BUILD_PATH));
app.use('*', function (req, res) {
return res.sendFile(BUILD_PATH + '/index.html');
});
const server = app.listen(3000, () => {
const host = server.address().address;
const port = server.address().port;
console.log('server is start at', host, port);
});
正常启动
还需要看什么代码,可以回复我
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
服务端渲染的关于css配置是什么,还有服务端渲染启动的时候不是要先把前端代码打包,生成一个有内容的html,然后启动服务,用户访问,后台直接返回这个有内容的html吗?看你这个express配置的逻辑是对的,但是报错信息像是没有经过打包前端代码,css还是模块化引入