CSS代码与Webpack 2和React路由器分离

Mat*_*ima 7 reactjs webpack css-modules webpack-2 extract-text-plugin

我是用我的代码将我的JavaScript文件与React Router和Webpack 2分开:

export default {
  path: '/',
  component: Container,
  indexRoute: {
    getComponent(location, cb) {
      if (isAuthenticated()) {
        redirect();
      } else {
        System.import('../landing-page/LandingPage')
          .then(loadRoute(cb))
          .catch(errorLoading);
       }
    },
  },
  childRoutes: [
    {
      path: 'login',
      getComponent(location, cb) {
        System.import('../login/Login')
          .then(loadRoute(cb))
          .catch(errorLoading);
      },
    },
    { /* etc */ 
    }
};
Run Code Online (Sandbox Code Playgroud)

这个捆绑包的结果如下:

public/
  vendor.bundle.js
  bundle.js
  0.bundle.js
  1.bundle.js
  2.bundle.js
Run Code Online (Sandbox Code Playgroud)

这意味着最终用户只能获得他/她所需的JavaScript,根据他/她所处的路线.

问题是:对于css部分,我找不到任何资源来做同样的事情,即根据用户的需要拆分CSS.

有没有办法用Webpack 2和React Router做到这一点?

m1k*_*ael 2

是的,这是可以做到的。CommonsChunkPlugin除了 之外,您还需要ExtractTextPlugin. 另外,定义多个入口点

entry: {
    A: "./a",
    B: "./b",
    C: "./c",
},
Run Code Online (Sandbox Code Playgroud)

并配置ExtractTextPlugin使用入口点名称作为 CSS 文件名

new ExtractTextPlugin({
    filename: "[name].css"
}),
Run Code Online (Sandbox Code Playgroud)

请参阅此处的完整示例:

https://github.com/webpack/webpack/tree/master/examples/multiple-entry-points-commons-chunk-css-bundle