【问题标题】:ReactJS - including other scss files in main.scssReactJS - 包括 main.scss 中的其他 scss 文件
【发布时间】:2018-02-12 03:02:26
【问题描述】:

在我的 reactJS 应用程序中 - 我将所有 .scss 文件包含在一个 main.scss 文件中 - 在 src 文件夹中的样式文件夹下。我有以下 webpack 配置。尝试将 main.scss 文件直接包含在我的主要组件中 - 在我导入其他 scss 文件的“@import”处出现错误。如果我包含单独的 scss 文件样式很好 - 但是如何使用一个 main.scss 文件以及如何包含它?

错误:意外令牌,预期 ((1:8)

1 | @import '我的组件';

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

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));
  });
}

【问题讨论】:

  • 你能添加你得到的错误和导入语句吗
  • 您需要在运行服务器代码之前对其进行转译。您将需要一个客户端 webpack 配置和一个服务器 webpack 配置。

标签: reactjs sass-loader webpack-loader


【解决方案1】:

您应该在顶级 React 组件中通过 javascript 导入您的 .scss 文件。

import './styles/main.scss';

Webpack 然后会将它包含在你的包中。

对于生产,您需要使用 Extract Text Plugin 用于 webpack,它将从 import 语句中导出一个单独的 css 文件。

【讨论】:

  • 更新了我的 webpack 文件和 index.js(react 应用程序的起点) - 这是一个服务器端渲染应用程序 - 使用上面的代码 - 我看到 Unexpected token, expected ( (1:8) > 1 | @import '组件';
  • @monkeyjs 我明白了。如果你想通过 webpack 导入你的 scss,你需要在运行它之前编译你的服务器代码。 github.com/realseanp/isomorphic-redux-react-webpack-starter 有一个例子说明怎么做
  • 转译你的服务器代码我的意思是你需要使用 webpack 来捆绑你的服务器代码和你的客户端代码。
【解决方案2】:

以下设置对我有用。

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/
  }

在顶部 index.js 中

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

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";

【讨论】:

    【解决方案3】:

    Webpack 对 .js 文件进行操作。您需要使用ExtractTextPlugin 将您的.scss 转换为.css 文件:

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

    将您的 webpack 入口点设置为您的main.scss 文件所在的目录,然后在该目录中创建一个 index.js 并使用以下行:

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

    您在此处包含的路径:&lt;link rel="stylesheet" type="text/css" href="./styles/main.scss"&gt; 应该是生成的.css 文件的路径。

    【讨论】:

      【解决方案4】:

      我会按照你的方式导入它们,不要重复使用 id 或类名,除非你希望样式相同:

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

      诸如此类

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-17
        • 2021-08-03
        • 2017-03-20
        • 1970-01-01
        • 2017-08-10
        • 2020-08-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多