简体   繁体   English

ReactJS - 包括main.scss中的其他scss文件

[英]ReactJS - including other scss files in main.scss

In my reactJS application - I am including all .scss files in one main.scss file - under styles folder in src folder. 在我的reactJS应用程序中 - 我将所有.scss文件包含在一个main.scss文件中 - 在src文件夹中的styles文件夹下。 I have the following webpack configuration. 我有以下webpack配置。 tried including main.scss file directly in my main component - getting error at '@import' where I import other scss files. 尝试将main.scss文件直接包含在我的主要组件中 - 在'@import'中获取错误,我导入其他scss文件。 if i include separate scss file styles are fine - but how to get this working with one main.scss file and how to include it? 如果我包含单独的scss文件样式是好的 - 但如何使用一个main.scss文件以及如何包含它?

error: Unexpected token, expected ( (1:8) 错误:预期的意外令牌((1:8)

1 | 1 | @import 'mycomponent'; @import'mycomponent';

module.exports = {
  entry: [
    'webpack-hot-middleware/client',
    path.resolve(__dirname, 'src'),
  ],
  output: {
    path: path.resolve(__dirname, 'src'),
    filename: 'bundle.js',
    publicPath: '/',
  },
  plugins: [
    new ExtractTextPlugin('bundle.css', { allChunks: true }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development'),
        WEBPACK: true,
      },
    }),
  ],
  module: {

    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          query: {
            presets: ['react-hmre'],
          },
        },
        include: path.resolve(__dirname, 'src'),
      },
     {
    use: ExtractTextPlugin.extract({
      fallback: "style-loader",
      use: [
         'css-loader', 
         'sass-loader?outputStyle=expanded'.
      ]
    }),
    test: /\.scss$/,
    exclude: /node_modules/
  }
    ],
  },
};

index.js index.js

import React from 'react';
import { render } from 'react-dom';
import { createBrowserHistory } from 'history';
import { ConnectedRouter, routerMiddleware } from 'react-router-redux';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/homepage';
import reducers from './reducers';
import '../styles/main.scss';


const history = createBrowserHistory();
const store = createStore(reducers, applyMiddleware(routerMiddleware(history)));

render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>
  , document.getElementById('app'));

if (process.env.NODE_ENV === 'development' && module.hot) {
  module.hot.accept();
  module.hot.accept('./reducers', () => {
    const nextRootReducer = require('./reducers').default; // eslint-disable-line global-require
    store.replaceReducer(nextRootReducer(store.asyncReducers));
  });
}

You should import your .scss file via javascript in your top level React component. 您应该在顶级React组件中通过javascript导入.scss文件。

import './styles/main.scss';

Webpack will then include it in your bundle. 然后,Webpack会将其包含在您的捆绑包中。

For production you will want to use the Extract Text Plugin for webpack which will export a separate css file from the import statement. 对于生产,您将需要使用Webpack的Extract Text Plugin ,它将从import语句中导出单独的css文件。

Webpack operates on .js files. Webpack在.js文件上运行。 You need to convert your .scss into a .css file using the ExtractTextPlugin : 您需要将您的转换.scss.css使用文件ExtractTextPlugin

{test: /\.scss$/,
    use: ExtractTextPlugin.extract({
        fallback: "style-loader",
        use: [{
            loader: "css-loader" // translates CSS into CommonJS
        }, {
            loader: "sass-loader"
        }]
    })
}

Set your webpack entry point for this to the directory in which your main.scss file lives, then create an index.js in that directory with the following line: 将此webpack入口点设置为main.scss文件所在的目录,然后使用以下行在该目录中创建index.js

require("./main.scss") (or import ./main.scss ) require("./main.scss") (或import ./main.scss

The path you include here: <link rel="stylesheet" type="text/css" href="./styles/main.scss"> should be the path to the generated .css file. 您在此处包含的路径: <link rel="stylesheet" type="text/css" href="./styles/main.scss">应该是生成的.css文件的路径。

Below settings work for me. 以下设置适合我。

webpack.config.js webpack.config.js

{
    use: ExtractTextPlugin.extract({
      fallback: "style-loader",
      use: [
         'css-loader', //knows how to deal with css
         'autoprefixer-loader?browsers=last 3 versions',
         'sass-loader?outputStyle=expanded' //this one is applied first.
      ]
    }),
    test: /\.scss$/,
    exclude: /node_modules/
  }

in the top index.js 在顶部index.js

import "./styles/main.scss";
import "./reactApp";

example of main.scss main.scss的例子

// Import any of your custom variables for bootstrap here first.
@import "my-theme/custom";
// Then, import bootstrap scss
@import "~bootstrap/scss/bootstrap";  
//for bootstrap 3 using bootstrap-sass
$icon-font-path: '~bootstrap-sass/assets/fonts/bootstrap/';
@import '~bootstrap-sass/assets/stylesheets/_bootstrap.scss';
// Finally import any custom styles.
@import "my-theme/master-theme";

I would just import them the way you are doing and dont reuse id or class names unless you want the styles to be the same so: 我只是按照你的方式导入它们,不要重复使用id或类名,除非你希望样式是相同的,所以:

import '../styles/main1.scss';
import '../styles/main2.scss';
....

Like that and so on 像那样等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM