Why is Webpack ignoring my CSS files?

2019-07-28 03:17发布

I'm trying to get webpack to compile my CSS files (using PostCSS) to a separate file. From the documentation, it seems like this is exactly what ExtractTextPlugin should do. However, I cannot get webpack to do anything at all with my CSS files.

The relevant project structure:

dist
 ⎣js
   ⎣bundle.js
public
 ⎣css
   ⎣style.css*
src
 ⎣css
   ⎣index.css

* file doesn’t exist (hasn’t been created)

webpack.config.babel.js

import webpack from 'webpack';
import path from 'path';

import ExtractTextPlugin from 'extract-text-webpack-plugin';

import { WDS_PORT } from './src/shared/config';
import { isProd } from './src/shared/util';

export default {
  entry: [
    'react-hot-loader/patch',
    './src/client',
  ],
  output: {
    filename: 'js/bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: isProd ? '/static/' : `http://localhost:${ WDS_PORT }/dist/`,
  },
  module: {
    rules: [
      { test: /\.(js|jsx)$/, use: 'babel-loader', exclude: /node_modules/ },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'style-loader',
            },
            {
              loader: 'css-loader',
              options: {
                sourceMap: true,
                importLoaders: 1,
              },
            },
            {
              loader: 'postcss-loader',
              options: {
                sourceMap: 'inline',
              },
            },
          ],
        }),
      },
    ],
  },
  devtool: isProd ? false : 'source-map',
  resolve: {
    extensions: ['.js', '.jsx', '.css'],
  },
  devServer: {
    port: WDS_PORT,
    hot: true,
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new ExtractTextPlugin('./public/css/style.css'),
  ],
};

This will happily compile my javascript correctly, but it does nothing at all to my CSS. What's going wrong, and how do I fix it?

1条回答
该账号已被封号
2楼-- · 2019-07-28 04:07

Webpack only processes files that are being imported at some point. That is either specified as an entry point or being imported in any file referenced from an entry point. The rules don't import any files, they are simply applied whenever an import passes the test (matches the regular expression in your case).

You need to import your CSS just like any other module.

import './css/index.css';

See also Code Splitting - CSS.

查看更多
登录 后发表回答