webpack 没有生成 css 文件

webpack not generating css file

正在执行 webpack asset management tutorial。但是 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());

Problem

图像在构建文件夹中很好地创建

但是

它没有在构建文件夹中创建 style.css,我做错了什么?

webpack 不会创建单独的 css 文件。它与 javascript 捆绑在一起,并通过 webpack bootstrap 代码作为 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"),
  ]
}

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',
        ],
      },
    ],
  },
};