preface

After configuring the REACT SSR environment, data isomorphism, and routing isomorphism, you need to process resources. Because a project can’t just have HTML JS, it also needs to deal with commonly used resources.

CSS Resource Handling

There are a lot of ways to write CSS, but I’ll deal with two common cases:

  • css in jsExamples are:styled-components
  • cssDirectly introducing

css in js

Styled Components, for the style network, are also useful if you haven’t used them.

styled-components

Install dependencies

$ npm i styled-components -D
Copy the code

Start by defining a Div to use in the component

import styled from 'styled-components';
const Div = styled.div` font-size: 20px; color: blue; span { color: red; font-size: 18px; } `;
const Index = (props) = >{...return (
    <Div>
      page: Fruit
      <span>I am {info.name}</span>
    </Div>)};Copy the code

On the server side, the exported ServerStyleSheet object can be styled-components. After instantiating the object, two main methods are used: collectStyles and getStyleTags, which, as the name implies, collectStyles and export style tags.

import { ServerStyleSheet } from 'styled-components';

export default async (req, res, next) => {
  ...
  const reactStr = renderToString(
    sheet.collectStyles(  // Collect styles
      <StaticRouter location={path} context={context}>
        <App />
      </StaticRouter>));const htmlInfo = {
    reactStr,
    initialData: JSON.stringify(initialData),
    styles: sheet.getStyleTags()    }; . }Copy the code

At this pointcss in js (styled-components) ssrAnd you’re done.

Complete code (SSR-CSS-IN-JS)

CSS Resource Handling

Install dependencies

$ npm i css-loader mini-css-extract-plugin -D
Copy the code

Css-loader is used for processing CSS files, and if styled-loader is used directly, the style processing is placed in JS and the style writing is handled through dom. However, as SSR is now used, this cannot be the case. Of course, isomorphic-style-loader can be used to write the style into the head on the server side, which is also no problem. The mini-CSS-extract-plugin is used to integrate CSS resources into CSS files.

The client WebPack configuration file needs to add the following:

{ // ...
  module: {
    rules: [{
      test: /.css$/,
      use: [MiniCssExtractPlugin.loader, 'css-loader']]}},plugins: [
    new MiniCssExtractPlugin({
      filename: 'index.css']}}),Copy the code

Although the client is already configured to generate CSS resources, the server will import CSS resources when compiling. This problem needs to be resolved. The server does not need to import CSS files at compile time because it carries the client-generated CSS files with it when it outputs content directly.

Solutions:

  • Loader processing
  • Plugin for processing
  • Babel plugin to handle

Return null ();

module.exports = () = > {  // ssr-css/webpack/loader/css-remove-loader.js
  return 'module.exports = null';
};
Copy the code

For loader, the result of the previous loader is used as a parameter. If it is the last loader, it needs to return javascript code.

Then we add and configure the loader in the server webpack

{ // ...
  module: {
    rules: [{
      test: /.css$/,
      loader: './webpack/loader/css-remove-loader'}]}}Copy the code

Finally, add a CSS resource reference to our HTML concatenation function.

<link rel="stylesheet" href="/index.css"></link>
Copy the code

At present, only a simple processing of CSS resources, assuming that the CSS resources are very large, then need to be divided, otherwise every time you modify a page of the file, it will lead to the CSS file cache invalidation, not very friendly.

Complete Code (SSR-CSS)

Image resource processing

Install dependencies

$ npm i url-loader file-loader -D
Copy the code

Url-loader is used to convert small image resources into data BSE64, and file-loader is used to process large image resources.

Add something to the webpack.base configuration file

{ // ...
  test: /\.(jpg|png|jpeg)$/,
  use: [{
    loader: 'url-loader'.options: {
      limit: 10240.name: 'img/[name].[hash:7].[ext]'.esModule: false}}}]Copy the code

Optimization process

Because currently, js files are consolidated into a main.js, which is not very friendly. It contains a lot of things that don’t change for a long time, such as react react-dom, etc., so every time we modify the JS, it will invalidate the cache.

So for this problem, WebPack provides optimization optimization that allows you to extract code from this field.

{ // ...
  optimization: {
    splitChunks: {
      cacheGroups: {
        libs: {
          test: /node_modules/.// We subcontract dependencies
          chunks: 'initial'.name: 'libs'
        }
      }
    }
  }
}
Copy the code

After the client is compiled and packaged, there will be an additional libs.index.js file, which the HTML splicing function also needs to import.

<script type="text/javascript" src="/libs.index.js"></script>
Copy the code

Complete Code (SSR-Handle)

Other chapters:

React SSR Practice (1)

React SSR Practice (part 3)