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

时间:2016-09-09 06:05:49

标签: reactjs webpack isomorphic-style-loader

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

  

失败的上下文类型:未指定必需的上下文insertCss   在WithStyles(Logo)。检查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)

我试图包括(Logo.scss):

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

.root {

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

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

1 个答案:

答案 0 :(得分:1)

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

ContextProvider(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;

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