【问题标题】:How to precompile scss to a single css file in webpack?如何将scss预编译为webpack中的单个css文件?
【发布时间】:2017-02-28 16:14:36
【问题描述】:

在 webpack 中使用 React。 浏览了一些文章,但其中大多数建议为每个组件调用单独的 scss 文件。但我想像我们使用 grunt/gulp 一样将所有 css 预编译到整个应用程序的单个文件中。

【问题讨论】:

    标签: css reactjs sass webpack webpack-style-loader


    【解决方案1】:

    您可以使用 webpack-text-extract-pluggin 负责编译所有 css 文件并将它们捆绑在一个 index.css 文件中。

    另请注意,您还需要安装 sass-loader 才能编译 scss。

    在 webpack 配置中:

    var ExtractTextPlugin = require('extract-text-webpack-plugin');
    config = {
        ..., 
        plugins: [
            ...,
            new ExtractTextPlugin('index.css')
        ],
        module: {
            loaders: [
                ...
                {
                    test: /\.css$/,
                    loader: ExtractTextPlugin.extract('style','css')
                },
                {
                    test: /\.scss$/,
                    loader: ExtractTextPlugin.extract('style', 'css!sass')
                }
            ]
        }
    }
    

    在 index.html 中:

    <link rel="stylesheet" type="text/css" href="/index.css">
    

    在任何通过 webpack 获取的 Javascript 文件中:

    require("./styles/my-custom-file.scss");
    

    【讨论】:

      【解决方案2】:

      你可以看看extract-text-webpack-plugin

      在你的 webpack.config.js 中要求这个之后:

      var ExtractTextPlugin = require("extract-text-webpack-plugin");
      

      您可以将您的 sass 加载器重写为:

      module: {
          loaders: [
              {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
              {test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css', 'sass')}
          ]
      },
      plugins: [
          new ExtractTextPlugin('bundle.css')
      ]
      

      有关更多选项和用法,请查看上面的链接。

      【讨论】:

      • 感谢@erik-Martijn
      猜你喜欢
      • 2017-03-14
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 2018-12-02
      • 2019-12-05
      • 2020-10-25
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多