如何使用Typescript,React和Webpack导入SCSS或CSS模块

时间:2019-05-14 14:42:06

标签: javascript css typescript webpack css-modules

我想在项目中使用.scss(带有react和typescript的辫子),所以我将typings-for-css-modules-loadercss-loadersass-loader一起使用。

npm run dev出现此错误:

./src/Common.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/lib/loader.js):

.common {
^
      Invalid CSS after "e": expected 1 selector or at-rule, was "exports = module.ex"

我的.scss是这样的:

.common {
  height: 100px
}

我的wepack.config是:

module.exports = {
    mode: 'development',
    entry: [
        'webpack-dev-server/client',
        path.resolve(root, 'src/index.tsx')
    ],
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './dist',
        publicPath: '/',
        port: 8080,
        historyApiFallback: true
    },
    resolve: {
        extensions: [".ts", ".tsx", ".scss", ".js", ".json", "css"]
    },
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new BundleAnalyzerPlugin(),
        new MiniCssExtractPlugin({
            filename: devMode ? '[name].css' : '[name].[hash].css',
            chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
        })
    ],
    output: {
        filename: 'bundle.js',
        path: path.resolve(root, 'dist'),
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader'
            },
            {
                test: /\.(js|jsx)$/,
                use: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(sa|sc|c)ss$/,
                use: [{
                    loader: devMode ? MiniCssExtractPlugin.loader : 'style-loader'
                }, {
                    loader: 'css-loader',
                    options: {
                        sourceMap: true,
                        modules: true,
                    }
                }, {
                    loader: 'sass-loader', options: {
                        sourceMap: true
                    }
                }]
            },
            { test: /\.(c|sc)ss$/, loader: 'typings-for-css-modules-loader?modules&sass' },
            {
                test: /\.(jpg|png|gif)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name (file) {
                            if (devMode === 'development') {
                              return '[path][name].[ext]'
                            }

                            return '[hash].[ext]'
                        }
                    }
                }]
            }
        ]
    },
    optimization: {
        splitChunks: {
            chunks: 'all'
        }
    }
};

当我将css-loadersass-loader一起使用或一次使用typings-for-css-modules-loader时,此错误已解决。

但是我又遇到了这样的错误:

ERROR in /Users/hly/Bpeanut.github.io/src/app/HeaderBar.tsx
./src/app/HeaderBar.tsx
[tsl] ERROR in /Users/hly/Bpeanut.github.io/src/app/HeaderBar.tsx(40,39)
      TS2339: Property 'header' does not exist on type 'typeof import("/Users/hly/Bpeanut.github.io/src/app/HeaderBar.scss")'.

HeaderBar.tsx像这样(错误在这里):

import * as styles from './HeaderBar.scss';

class default HeaderBar extends Component {
    render() {
        return(<div className={styles.header}>123</div>)
                                        ^
    }
}

HeaderBar.scss,例如:

.header {
    height: 100px;
}

HeaderBar.scss.d.ts

export interface IHeaderBarScss {
  'header': string;
}

export const locals: IHeaderBarScss;

现在我找到了另一种解决方法。

使用const styles = require('./HeaderBar.scss');代替import * as styles from './HeaderBar.scss';

它有效。

谢谢。

2 个答案:

答案 0 :(得分:0)

对于带有CSS和CSS的项目,我不使用typings-for-css-modules-loader,并且在此配置下,效果很好:

{
    test: /\.s?css$/,
    use: [
        {
            loader: MiniCssExtractPlugin.loader,
            options: {
                sourceMap: true
            }
        },
        {
        loader: 'css-loader',
            options: {
                sourceMap: true
            }
        },
        {
            loader: 'sass-loader',
            options: {
                sourceMap: true
            }
        }
    ]
},

这可以解决您的错误吗?

答案 1 :(得分:0)

用css-loader和style-loader绑定sass-loader,以立即将所有样式应用于DOM。

let arr = [4,-2,-3,5,1,10]

function findNums(arr,sum){
  let obj = {}
  let temp = 0;
  for(let i = 0;i<arr.length;i++){
    temp += arr[i];
    if(temp === sum) return arr.slice(0,i+1);
    if(obj[temp - sum] != undefined){
      if(obj[temp-sum]+1 !== i){
        return arr.slice(obj[String(temp - sum)]+1,i+1);
      }
    }
    obj[temp] = i;
  }
  return [];
}


console.log(findNums(arr,0))
console.log(findNums(arr,-1))
console.log(findNums(arr,13))
console.log(findNums(arr,1))

// webpack.config.js

npm install style-loader css-loader sass-loader --save-dev

有关更多信息,请访问sass loader