简体   繁体   English

[Webpack] [反应]在具有代码拆分功能的SSR上,如何获取页面所需的块列表?

[英][Webpack][React] On SSR with code-splitting how I can get the list of chunks needed by the page?

I've a React application with perfectly working SSR and Webpack code-splitting. 我有一个React应用程序,具有完美的SSR和Webpack代码拆分功能。

My webpack.config.js looks like this: 我的webpack.config.js看起来像这样:

const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ServerMiniCssExtractPlugin = require("./server/utils/serverMiniCssExtractPlugin");

module.exports = [{
  name: 'react-app',
  mode: 'development',
  devtool: 'eval',
  cache: true,
  entry: {
    main: [
      'babel-polyfill',
      'webpack-hot-middleware/client',
      './react/index.tsx',
    ],
  },
  output: {
    path: `${__dirname}/dist/__build__`,
    filename: '[name].js',
    chunkFilename: '[name].js',
    publicPath: '/__build__/',
  },
  module: {
    rules: [{
      test: /\.(ts|js)x?$/,
      loader: 'babel-loader',
      exclude: [/node_modules/],
    }, {
      test: /\.scss$/,
      oneOf: [{
        resourceQuery: /^\?raw$/,
        use: [MiniCssExtractPlugin.loader, {
          loader: 'css-loader',
          options: {
            modules: true,
            sourceMap: true,
            camelCase: false,
            localIdentName: '[local]',
          },
        }, 'sass-loader', 'postcss-loader'],
      }, {
        use: [MiniCssExtractPlugin.loader, {
          loader: 'css-loader',
          options: {
            modules: true,
            sourceMap: true,
            camelCase: true,
            localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
          },
        }, 'sass-loader', 'postcss-loader'],
      }]
    }],
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        CLIENT: JSON.stringify(true),
      },
    }),
    new webpack.IgnorePlugin(/^vertx$/),
    new MiniCssExtractPlugin({
      filename: "style.css",
      chunkFilename: "style.chunk.[id].css"
    }),
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /node_modules/,
          name: 'vendor',
          enforce: true
        },
      },
    },
  },
}, {
  name: 'server-side rendering',
  mode: 'development',
  devtool: 'eval',
  cache: true,
  entry: [
    './react/ssr.tsx',
  ],
  target: 'node',
  output: {
    path: `${__dirname}/dist/__server__/`,
    filename: 'ssr.js',
    publicPath: '/__server__/',
    libraryTarget: 'commonjs2',
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
  },
  module: {
    rules: [{
      test: /\.(ts|js)x?$/,
      exclude: [/node_modules/, /.+\.config.js/],
      loader: 'babel-loader',
    }, {
      test: /\.scss$/,
      oneOf: [{
        resourceQuery: /^\?raw$/,
        use: [ServerMiniCssExtractPlugin.loader, {
          loader: 'css-loader',
          options: {
            modules: true,
            sourceMap: true,
            camelCase: false,
            localIdentName: '[local]',
          },
        }, 'sass-loader', 'postcss-loader'],
      }, {
        use: [ServerMiniCssExtractPlugin.loader, {
          loader: 'css-loader',
          options: {
            modules: true,
            sourceMap: true,
            camelCase: true,
            localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
          },
        }, 'sass-loader', 'postcss-loader'],
      }]
    }],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        SERVER: JSON.stringify(true),
      },
    }),
    new webpack.IgnorePlugin(/^vertx$/),
    new ServerMiniCssExtractPlugin({
      filename: "style.css",
      chunkFilename: "style.chunk.[id].css"
    }),
  ],
}];

... and it generates chunks for both js and css that using the app are loaded correctly when moving from the different pages, all mapped with react-router. ...并且它为js和css生成块,这些块从不同页面移动时正确地加载了使用该应用程序的所有页面,所有页面均由react-router映射。

The problem is that when I reload one of the pages the needed css chunks are loaded once rendered and not linked directly in the page from the SSR, so for a second I have FOUC . 问题是,当我重新加载其中一个页面时,所需的css块在呈现后即被加载,并且没有从SSR直接链接到页面中,因此有一秒钟我有了FOUC

Since I would like using React-Helmet to inject in the page head the needed css chunks when I SSR the app how I can get in the code the list of chunks file names that are needed for the page that I reload? 由于我想使用React-Helmet在我对应用程序进行SSR时向页面头部注入所需的css块,我如何才能在代码中获取重新加载页面所需的块文件名列表?

Let say that the page needs: 0.js 2.js style.chunk.0.css style.chunk.2.css 假设该页面需要:0.js 2.js style.chunk.0.css style.chunk.2.css

How I can get the list of these files so I can generate dynamically the links in the page head? 如何获取这些文件的列表,以便动态生成页面头中的链接?

Thanks. 谢谢。

Use the webpack-manifest-plugin to generate a manifest.json file that will include a list of all your chunks. 使用webpack-manifest-plugin生成manifest.json文件,其中将包含所有块的列表。

In your webpack.config.js : 在您的webpack.config.js

var ManifestPlugin = require('webpack-manifest-plugin');

module.exports = {
    // ...
    plugins: [
      new ManifestPlugin()
    ]
};

This will generate a manifest.json file in your root output directory with a mapping of all source file names to their corresponding output file, for example: 这将在根输出目录中生成一个manifest.json文件,该文件具有所有源文件名到其对应输出文件的映射,例如:

{
  "mods/alpha.js": "mods/alpha.1234567890.js",
  "mods/omega.js": "mods/omega.0987654321.js"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应路由器基本代码拆分(获取第一个块,然后在后台异步获取其他块) - React router base code-splitting (get first chunk and then get other chunks async in background) 如何让 webpack-dev-server 停止使用 React 惰性/Suspense 代码拆分来停止下载内容更改时不正确的块? - How can I get webpack-dev-server to stop downloading incorrect chunks on content change with React lazy/Suspense code splitting? 使用webpack和react-router进行延迟加载和代码分割无法加载 - Using webpack and react-router for lazyloading and code-splitting not loading 是否添加.default?:反应路由器3中的动态导入webpack代码拆分 - to add .default or not?: dynamic imports in react router 3 for webpack code-splitting 使用webpack,bundle-loader react-router进行隐式代码分割 - Implicitly code-splitting with webpack, bundle-loader react-router Webpack代码拆分包托管在两个服务器上 - Webpack code-splitting bundles hosted over two servers 使用Ruby On Rails App中的Webpack在ReactJS组件中进行代码拆分 - Code-Splitting in ReactJS Components with Webpack in Ruby On Rails App Webpack:了解块和代码拆分 - Webpack: Understanding chunks and code splitting 反应样板中的代码拆分和异步代码加载 - Code-splitting and async code loading in react-boilerplate 反应代码拆分:ChunkLoadError:加载块 0 失败 - React Code-Splitting: ChunkLoadError: Loading chunk 0 failed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM