When webpack packaged the release script to NPM, the code did not change at all. When vscode was opened again, something strange happened, and errors were reported after compiling

 // webpack4=>5
 // I was depressed for a while because of this plugin (brain buzzing, I learned a few days ago is fake? Why not?)
 new webpack.ProvidePlugin({
    process: "process/browser",}).Copy the code

Back to business:

1. Server rendering is packaged with Webpack

Go straight to code

if (typeof window= = ="undefined") {
  global.window = {};
  global.self = {};
}

const express = require("express");
const fs = require("fs");
const path = require("path");
const { renderToString } = require("react-dom/server");
const SSR = require(".. /dist/search-serve");
// Set the port

// Mock any data
const data=require("./data.json")

const template=fs.readFileSync(path.join(__dirname,'.. /dist/search.html'),'utf8');

const server = (port) = > {
  const app = express();
  // Set the static directory
  app.use(express.static("dist"));
  // Set the route
  app.get("/search".(req, res) = > {
    const html = renderMarkup(renderToString(SSR));
    res.status(200).send(html);
  });
  app.listen(port, () = > {
    console.log("server listening on port" , port);
  });
};

server(process.env.PORT || 3000);


const renderMarkup = (str) = > {
  const dataStr=JSON.stringify(data)
  // Use placeholder substitution here
  // Do not write directly using HTML templates to solve the problem of style failure
  return template.replace('<! --HTML_REPLACE-->',str).replace('<! --DATA-->'.`<script>window.__initial_data=${dataStr}</script>`);
};

Copy the code
// Placeholders need to be reserved in HTML
<body>
  <div id="root"><! --HTML_REPLACE--> <! --DATA--></div>
</body>
Copy the code

I also studied the loader for a long time (speechless), and later found that there was no request for the style file, so I found the placeholder method

const logo = require("./images/loaders.png").default;
Copy the code

Step on pit 3: the picture is missing, this is my first time to write the introduction of such a picture code (really meal ah)

2. Stats

I use Webpack5, so “friendly-errors-webpack-plugin” and stats are not used, and compilation results and problems can be clearly seen, so I don’t pay too much attention to them

I have something to say about stomping pits:

1, the pit is not terrible, terrible is not solved around (dev, pro is of course a quick solution)

2. Pay attention to the error prompt and accurately locate the cause of the error

(Because it is a waste of time to step on pits, let’s stop here today!)

Github address: github.com/838216870/w…