SCSS编译在同构React应用程序中

时间:2016-08-01 23:03:29

标签: reactjs sass webpack isomorphic-javascript webpack-style-loader

我正在编写一个基于以下内容的同构React应用程序:

https://github.com/choonkending/react-webpack-node

不是使用示例中使用的css模块,而是喜欢使用scss。出于某种原因,我很难让他们上班。我的第一步是从服务器和客户端configs中删除css webpack加载器,将其替换为scss - 特定加载器(以及删除postcss):< / p>

  loaders: [
    'style-loader',
    'css-loader?modules&localIdentName=[name]_[local]_[hash:base64:3]',
    'sass-loader?sourceMap',
  ]

但是当构建为样式加载器时,这会抛出ReferenceError: window is not defined,显然不适合服务器端呈现。所以我的下一个想法是使用isomorphic-style-loader。据我所知,为了让它工作,我需要使用更高阶的组件withStyles来装饰我的组件:

import React, { PropTypes } from 'react';
import classNames from 'classnames';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from '../assets/scss/common/index.scss';

const App = (props, context) => (
  <div className={classNames('app')}>
    <h1 className="home_header">Welcome!</h1>
    {props.children}
  </div>
);

export default withStyles(s)(App);

然后在服务器上的代码呈现页面中做一些技巧。但问题是,包文档中的示例显示了在Express(https://libraries.io/npm/isomorphic-style-loader#webpack-configuration)内部触发的磁通动作,以及我使用的样板react-router。所以我有点失落,因为我应该如何将insertCss这个对象注入上下文中。我试过这个:

import React from 'react';
import { renderToString } from 'react-dom/server';
import { RouterContext, match, createMemoryHistory } from 'react-router';
import axios from 'axios';
import { Provider } from 'react-redux';
import createRoutes from 'routes.jsx';
import configureStore from 'store/configureStore';
import headconfig from 'components/Meta';
import { fetchComponentDataBeforeRender } from 'api/fetchComponentDataBeforeRender';

const clientConfig = {
  host: process.env.HOSTNAME || 'localhost',
  port: process.env.PORT || '3001'
};

// configure baseURL for axios requests (for serverside API calls)
axios.defaults.baseURL = `http://${clientConfig.host}:${clientConfig.port}`;

function renderFullPage(renderedContent, initialState, head = {
  title: 'cs3',
  css: ''
}) {
  return `
  <!DOCTYPE html>
  <html lang="en">
  <head>
    ${head.title}
    ${head.link}
    <style type="text/css">${head.css.join('')}</style>
  </head>
  <body>
    <div id="app">${renderedContent}</div>
    <script type="text/javascript">window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};</script>
    <script type="text/javascript" charset="utf-8" src="/assets/app.js"></script>
  </body>
  </html>
  `;
}

export default function render(req, res) {
  const history = createMemoryHistory();
  const store = configureStore({
    project: {}
  }, history);

  const routes = createRoutes(store);

  match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
    const css = [];

    if (error) {
      res.status(500).send(error.message);
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if (renderProps) {
      const context = { insertCss: (styles) => css.push(styles._getCss()) };

      const InitialView = (
        <Provider context={context} store={store}>
            <RouterContext {...renderProps} />
        </Provider>
      );

      fetchComponentDataBeforeRender(store.dispatch, renderProps.components, renderProps.params)
      .then(() => {
        const componentHTML = renderToString(InitialView);
        const initialState = store.getState();
        res.status(200).end(renderFullPage(componentHTML, initialState, {
          title: 'foo',
          css
        }));
      })
      .catch(() => {
        res.end(renderFullPage('', {}));
      });
    } else {
      res.status(404).send('Not Found');
    }
  });
}

但是我仍然得到Warning: Failed context type: Required context 'insertCss' was not specified in 'WithStyles(App)'.任何想法如何解决这个问题?更重要的是 - 有没有更简单的方法呢?这似乎是很多额外的工作。

1 个答案:

答案 0 :(得分:1)

在进行服务器端渲染时,使用webpack处理scss编译有几个部分。首先,您不希望节点尝试将.scss文件导入您的组件。

因此,在webpack配置中设置全局变量WEBPACK: true

plugins: [
    new webpack.DefinePlugin({
        'process.env': {
            WEBPACK: JSON.stringify(true),
        }
    })
],

在您的组件中,如果组件由webpack处理(在构建或开发期间),则仅尝试导入.scss文件:

if (process.env.WEBPACK) require('../assets/scss/common/index.scss');

如果每个组件只有一个Sass文件(你应该),那么这只是一个单行。如果需要,可以在index.scss内导入任何其他Sass文件。

然后在你的配置中你可能仍然需要css加载器,所以对于你的开发服务器它应该是这样的:

{
    test: /\.s?css$/,
    loaders: ['style', 'css', 'sass']

},

这样的东西为你构建配置:

{
    test: /\.s?css$/,
    loader: ExtractTextPlugin.extract('style', 'css!sass')
},