如何让Stylus使用Webpack 3?

时间:2017-10-27 21:35:19

标签: webpack stylus webpack-style-loader

我真的很难让Stylus CSS预处理器使用当前版本的Webpack。这就是我的尝试:

webpack.config.js:

var path = require("path");
module.exports = {
    entry: './src/app.js',
    output: {
        filename: 'mwe.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                include: /src/
            },
            {
              test: /\.styl$/,
              include: /src/,
              use: [
                'style-loader',
                {
                  loader: 'css-loader',
                  options: {
                    modules: true,
                    localIdentName: '[name]__[local]___[hash:base64:5]'
                  }
                },
                'stylus-loader'
              ],
            },
        ]
    }
};

的package.json:

{
  ...
  "devDependencies": {
    "css-loader": "^0.28.7",
    "style-loader": "^0.19.0",
    "stylus": "^0.54.5",
    "stylus-loader": "^3.0.1",
    "webpack": "^3.8.1"
  }
}

/src内部我有一个非常简单的app.jsstyle.styl

当我运行Webpack时,/dist/mwe.js按预期生成,但我也希望从Stylus文件生成一个CSS文件。我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

如果您正在使用.css,则Webpack不会发出style-loader个文件。您需要使用ExtractTextPlugin来获取CSS文件。

答案 1 :(得分:1)

如Panya所述,您需要先安装ExtractTextPlugin

  1. npm i --save-dev extract-text-webpack-plugin
  2. 然后加入 你webpack.config.js
  3. const ExtractTextPlugin = require('extract-text-webpack-plugin');
    const extractPlugin = new ExtractTextPlugin({
      filename: '../css/style.css',
      allChunks: true,
    });
    
    const config = {
      …
      module: {
        rules: [
          {
            test: /\.(css|styl)$/,
            use: extractPlugin.extract({
              use: [
                {
                  loader: 'css-loader', 
                  options: {importLoaders: 1, sourceMap: true}
                },
                {
                  loader: 'stylus-loader',
                  options: { sourceMap: true },
                },
              ]
            })
          }
        ]
      },
      plugins: [extractPlugin]
      …
    }