如何使用 webpack 配置 isomorphic-style-loader 并做出反应?

How to configure isomorphic-style-loader with webpack and react?

我正在尝试使用 isomorphic-style-loader 配置 webpack,但我不断收到以下消息。 (我并不是真的需要使用同构,所以如果有更简单的方法来做到这一点,我不介意改变)。我需要的是 scss 个文件的范围。

Failed Context Types: Required context insertCss was not specified in WithStyles(Logo). Check the render method of Header.

这是我的 webpack.conf.js:

var path = require('path');

const BROWSERS_TO_PREFIX = [
  'Android 2.3',
  'Android >= 4',
  'Chrome >= 35',
  'Firefox >= 31',
  'Explorer >= 9',
  'iOS >= 7',
  'Opera >= 12',
  'Safari >= 7.1',
];

var config = module.exports = {
   context: path.join(__dirname,'..'),
   entry: './app/frontend/main.js',
   watchOptions : {
       aggregateTimeout: 100,
       poll: true
   }
};

config.output = {
   path: path.join(__dirname, '..', 'app', 'assets', 'javascripts'),
   filename: 'bundle.js',
   publicPath: '/assets',
   devtoolModuleFilenameTemplate: '[resourcePath]',
   devtoolFallbackModuleFilenameTemplate: '[resourcePath]?[hash]'

};

config.module = {
    include: [
      path.resolve(__dirname, '../node_modules/react-routing/src')
    ],
    loaders: [{
        test: /\.js$/,
        loader: 'babel',
        exclude: [
          '/node_modules/',
          '/assets/'
        ],
        query: {
          presets: ['es2015', 'stage-1', 'react']
        }
      },
      {
        test: /\.scss$/,
        loaders: [
          'isomorphic-style-loader',
          'css-loader?modules&localIdentName=[name]_[local]_[hash:base64:3]',
          'postcss-loader?parser=postcss-scss',
        ],
      }
    ]
};


config.resolve = {
    extensions: ['', '.js', '.jsx'],
    modulesDirectory: ['../node_modules']
};

config.postcss = function plugins(bundler) {
  return [
    require('postcss-import')({ addDependencyTo: bundler }),
    require('precss')(),
    require('autoprefixer')({ browsers: BROWSERS_TO_PREFIX }),
  ];
};

这是我的切入点 (main.js):

import Routes from './routes'
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';

const context = {
  insertCss: styles => styles._insertCss()
};

if (['complete', 'loaded', 'interactive'].includes(document.readyState) && document.body) {
  ReactDOM.render(Routes, document.getElementById("main"));
} else {
  document.addEventListener('DOMContentLoaded', () => {
    "use strict";
    ReactDOM.render(Routes, document.getElementById("main"));
  }, false);
}

这是我的路线 (routes.js):

import React, { Component, PropTypes } from 'react';
import App from './components/App';
import Login from './components/Login';
import Projects from './components/Projects';
import { Router, Route, IndexRoute, Link, browserHistory } from 'react-router'

let Routes = (
    <div className="container">
      <Router history={browserHistory}>
        <Route path={"/"}>
          <IndexRoute component={App} />
          <Route path={"/projects"} component={Projects} />
          <Route path={"/sign_in"} component={Login} />
        </Route>
      </Router>
    </div>
);

export default Routes;

引发错误的文件 (Logo.js):

从'react-router'导入ReactRouter,{withRouter,Link}; 从 'react' 导入 React,{ Component,PropTypes}; 从 'isomorphic-style-loader/src/withStyles' 导入 withStyles; 从 './Logo.scss';

导入 s
class Logo extends Component {
  render() {
    return (
      <Link to="/" class="image-link" id="logo-container">
        <img src="/images/spotscale-logo.png" id="spotscale-logo"/>
        <img src="/images/beta.png" id="beta-logo" />
      </Link>
    );
  }
}
export default withStyles(s)(Logo)

css 我试图包括 (Logo.scss):

@import '../../globals.scss';

.root {

  #beta-logo {
    width: 70px;
    position: relative;
    top: -34px;
    left: 8px;
  }
  #logo-container {
    padding: 2em 0em;
    display: inline-block;
  }
}

如果我更改行 withStyles(s)(Logo) 模板呈现但没有 css。我很确定问题是我在 Logo class 的上下文中需要一个名为 insertCss 的方法,但我不知道以什么方式将它获取到那里或者 thaht 方法应该是什么样子。任何帮助,将不胜感激。

问题是我怀疑上下文不包含 insertCss 方法。我必须做的是从一个中心位置提供上下文来解决这个问题。因此,我创建了一个 HOC(React 组件)来执行此操作,并将该组件用作我的根元素。

上下文提供者(HOC):

import s from '../general.scss';
class ContextProvider extends Component {

  static propTypes = {
    context: PropTypes.shape({
      insertCss: PropTypes.func,
    }),
    error: PropTypes.object,
  };

  static childContextTypes = {
    insertCss: PropTypes.func.isRequired,
  };

  getChildContext() {
    const context = this.props.context;
    return {
      insertCss: context.insertCss || emptyFunction,
    };
  }

  componentWillMount() {
    const { insertCss } = this.props.context;
    this.removeCss = insertCss(s);
  }

  componentWillUnmount() {
    this.removeCss();
  }

  render() {
    return <div id="context">{this.props.children}</div>
  }
}
export default ContextProvider;

修改后的路由:

import React, { Component, PropTypes } from 'react';
import ContextProvider from './components/ContextProvider'
import IndexPage from './components/IndexPage';
import LoginPage from './components/LoginPage';
import ProjectsPage from './components/ProjectsPage';
import { Router, Route, IndexRoute, Link, browserHistory } from 'react-router'


const context = {
  insertCss: styles => styles._insertCss(),
};

let Routes = (
    <ContextProvider className="container" context={context}>
      <Router history={browserHistory}>
        <Route path={"/"}>
          <IndexRoute component={IndexPage} />
          <Route path={"/projects"} component={ProjectsPage} />
          <Route path={"/sign_in"} component={LoginPage} />
        </Route>
      </Router>
    </ContextProvider>
);

export default Routes;

我希望这对其他人有帮助。询问您是否需要更多信息