webpack没有生成CSS文件。

10

实现webpack资产管理教程。但是webpack没有在输出路径中生成CSS文件。

webpack.config.js

const config = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: __dirname + '/build'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      },
      {
        test: /\.(jpeg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].[ext]'
            }
          }
        ]
      }
    ]
  }
};

index.js

  import './style.css';
  import Icon from './yo1.jpg';

  function component() {
    var element = document.createElement('div');

    element.innerHTML = 'hello webpack'
    element.classList.add('hello');

    var myIcon = new Image();
    myIcon.src = Icon;

    element.appendChild(myIcon);

    return element;
  }

  document.body.appendChild(component());

enter image description here

问题

图片已经在构建文件夹中创建好了,但是样式表style.css没有被创建到构建文件夹中,我做错了什么?

2个回答

9

webpack不会创建单独的CSS文件。它与JavaScript一起捆绑,并由webpack引导代码作为style标签注入到DOM中。

如果您想创建单独的CSS文件,可以使用ExtractTextPlugin插件 - https://github.com/webpack-contrib/extract-text-webpack-plugin

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

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
  ]
}

8

ExtractTextPlugin已被弃用,请尝试使用https://github.com/webpack-contrib/mini-css-extract-plugin代替:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // all options are optional
      filename: '[name].css',
      chunkFilename: '[id].css',
      ignoreOrder: false, // Enable to remove warnings about conflicting order
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it uses publicPath in webpackOptions.output
              publicPath: '../',
              hmr: process.env.NODE_ENV === 'development',
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接