Webpack-React与服务器端呈现:使用哈希名称链接到服务器模板中的css文件

问题描述 投票:6回答:2

我正准备从头开始做出反应,这是代码:https://github.com/antondc/react-starter

我设法为客户端和服务器设置捆绑,使用css模块和更少,现在我使用服务器端渲染。我是用js模板做的:

// src/server/views/index.ejs
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>INDEX.EJS</title>
    <link rel="stylesheet" type="text/css" href="assets/index.css">
</head>
<body>
    <div id="app"></div>
    <script src="/assets/bundle.js"></script>
</body>
</html>

如您所见,css文件的链接在那里被编码。但是在我的Webpack配置中,我有这个文件名哈希,因为我想在开发时更新代码时阻止浏览器的缓存。

我想知道如何在那里链接css文件。现在在模板中我有href="assets/index.css,但css文件在/dist/assets/d47e.css

如果有可能做像href="assets/*.css这样的事情会很棒,但是不可能,那么像这样的问题的常见方法是什么?

谢谢!

css reactjs webpack server-side
2个回答
2
投票

这取决于。

Step 1: Get the current asset name

要获取生成的webpack css / js文件的当前名称,可以使用assets-webpack-plugin。这将(使用默认配置)在输出文件夹中生成一个assets.json文件,基本上具有以下结构:

{
    "bundle_name": {
        "asset_kind": "/public/path/to/asset"
    }
}

Step 2a: Your html is rendered from a template (pug/jade/what ever)

// in your render code

const assets = require('<webpack-output-folder>/assets.json');

// ...

res.render('template', {
 scripts: [{src: `${WEBPACK_PUBLIC_PATH}/${assets.myEntryPointName.js}` }],
 links: [{href: `${WEBPACK_PUBLIC_PATH}/${assets.myEntryPointName.css}` rel: 'stylesheet' }],
});

// in your template (example for pug)

// ...

each link in links
  link(rel=link.rel href=link.href)

// ...

each script in scripts
  script(src=script.src)

// ...

Step 2b: Your html is static

您需要使用asset.json文件中的信息更新html(使用脚本)。此脚本需要在webpack之后运行。就像是

const assets = require('<webpack-output-folder>/assets.json');
const fs = require('fs');

const css = /assets\/[a-z0-9]*\.css/i;
const js = /assets\/[a-z0-9]*\.js/i;

fs.readFile('<yourhtml>.html', (err, data) => {

  // ... (error handling)

  const updatedCss = data.replace(css, assets.myEntryPointName.css);
  const updatedJs = updatedCss.replace(js, assets.myEntryPointName.js);

  fs.writeFile('<yourhtml>.html', updated, (err) => {

    // ... (error handling)

  });

});

0
投票

您可以使用HTMLWebpackPlugin生成一个HTML文件,该文件将插入您的JS和CSS输出。

© www.soinside.com 2019 - 2024. All rights reserved.