2

我正在尝试使用 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'导入反应,{组件,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;
  }
}

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

4

1 回答 1

1

问题在于我怀疑上下文不包含 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;

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

于 2016-09-09T07:51:35.563 回答