无法在反应中导入Sass文件

时间:2018-11-13 15:19:26

标签: reactjs typescript webpack sass

我正在使用以下样板:https://github.com/spravo/typescript-react-express

我设计了第一个组件:按钮

import * as React from 'react';

import './button.scss';

export interface IButton {
  value: string;
  onClick: () => void;
}

class Button extends React.Component<IButton, {}> {
  public render () {
    return (
      <div className='Button'>
        <button onClick={this.props.onClick} className='Button__btn'>
          {this.props.value}
        </button>
      </div>
    );
  }
}

export default Button;

在button.scss中,我有这条简单的线:

.Button {
  background-color: red;
}

但是出现以下错误:

(function (exports, require, module, __filename, __dirname) { .Button {

SyntaxError: Unexpected token .

这是我的webpack配置(与回购中的配置完全相同),但用于webpack迁移的config.common.js除外:

'use strict';

const path = require('path');
const webpack = require("webpack");

const config = require('../config')(process.env.NODE_ENV);
const vendors = require('./vendor');

const NODE_ENV = process.env.NODE_ENV || 'development';

module.exports = function getConfig(dirname) {
  return {
    target: 'web',
    context: path.resolve(dirname),
    stats: {
      chunks: false,
      colors: true,
    },
    entry: {
      vendor: vendors
    },
    resolve: {
      extensions: [ '.ts', '.tsx', '.js', '.scss', '.css' ],
      modules: [
        path.resolve(__dirname, '..', 'src'),
        path.resolve(__dirname, '..', 'node_modules'),

      ]
    },
    output: {
      path: config.PUBLIC_FOLDER,
      filename: '[name].[hash].js',
      chunkFilename: '[name].[chunkhash].js',
      publicPath: config.PUBLIC_PATH
    },
    module: {
      rules: []
    },
    optimization:{
      splitChunks:{
        name: 'vendor'
      }
    },
    plugins: [
      new webpack.NoEmitOnErrorsPlugin(),
      // new webpack.optimize.CommonsChunkPlugin({
      //   name: 'vendor'
      // }),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(NODE_ENV)
        },
        __CLIENT__: true,
        __SERVER__: false,
        __DEV__: NODE_ENV === 'development',
        __TEST__: false
      })
    ]
  };
};

Css加载程序:

'use strict';

const isDevelopment = (process.env.NODE_ENV || 'development') === 'development';
const autoprefixer = require('autoprefixer');


module.exports = {
  scssLoader: [
    {
      loader: 'css-loader',
      options: {
        minimize: !isDevelopment,
        sourceMap: isDevelopment
      }
    },
    {
      loader: 'postcss-loader',
      options: {
        sourceMap: isDevelopment,
        plugins: [
          autoprefixer({
            browsers:['ie >= 8', 'last 4 version']
          })
        ]
      }
    },
    {
      loader: 'sass-loader',
      options: {
        sourceMap: isDevelopment  
      }
    }
  ]
};

似乎唯一起作用的scss在styles / index.scss中,但是我不明白为什么它不占用其他scss文件。

我的tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "baseUrl" : "./src",
    "target": "es5",
    "jsx": "react",
    "alwaysStrict": true,
    "sourceMap": true,
    "outDir": "dist",
    "lib": [
      "dom",
      "es2015",
      "es5",
      "es6"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "typings"
  ],
  "exclude": [
    "node_modules"
  ]
}

1 个答案:

答案 0 :(得分:0)

您的webpack配置“ module.rules”是一个空数组真的很奇怪! 那是应该添加您的加载程序设置的地方。

如果我是您,我将复制css-loaders配置文件的内容并粘贴到您的webpack.config.js文件中。确保将其存储在普通变量/对象中,而不是在module.exports中。

这是我的webpack配置的样子:

const styleLoader = {
  test: /\.(scss)$/,
  include: path.resolve(__dirname, 'src'),
  use: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          sourceMap: true,
          minimize: true
        }
      }, {
        loader: 'postcss-loader',
        options: {
          sourceMap: true,
          config: {
            path: path.join(__dirname, 'postcss.config.js')
          }
        }
      }, {
        loader: 'sass-loader',
        options: { sourceMap: true }
      }
    ]
  })
};

然后我的webpack配置如下所示。请注意modules.rules部分:

module.exports = {
  entry: {
    app: ['babel-polyfill', 'whatwg-fetch', srcPath('index.js')],
    silentrenew: [srcPath('silentrenew.js')]
  },
  output: {
    path: path.resolve(__dirname, 'build'),
    publicPath: '/',
    filename: '[name].js'
  },
  devtool: 'source-map',
  plugins: [
    htmlPlugin('index.html', 'app'),
    new ExtractTextPlugin('bundle.css'),
  ],
  module: {
    rules: [
      babelLoader,
      fontLoader,
      svgLoader,
      styleLoader
    ]
  }
};