【问题标题】:Why aren't my stylesheets being included in the Webpack build?为什么我的样式表没有包含在 Webpack 构建中?
【发布时间】:2021-12-12 00:50:26
【问题描述】:

Webpack 将文件(.css、.js)收集到一个库中,并在另一个 React 项目中使用它。组件中指定的样式不会通过,尽管 .css 文件存在并且样式存在。

UiButton.jsx 文件

import styles from './UiButton.module.css';

const UiButton = () => {
    return (
        <>
            <button className={styles.button}>Text</button>
        </>
    );
}

export default UiButton;

index.js 文件

import UiButton from './UiButton/UiButton';
import './index.css';

export { UiButton };

Webpack.config.js 文件

const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  entry: { main: './src/index.js' },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index.js',
    libraryTarget: "umd",
    library: "uilibrarytest"
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.css$/,
        use:  [  'style-loader', MiniCssExtractPlugin.loader, 'css-loader' ]
      }
    ]
  },
  plugins: [ 
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
        filename: 'index.css',
    }),
    // new HtmlWebpackPlugin({
    //     template: './public/index.html',
    // }),
    new webpack.ProvidePlugin({
        "React": "react",
      }),
  ],
  resolve: {
    extensions: ['.js', '.jsx'],
  },
}

这是 webpack 构建的:

.button {
    background: red;
}
html {
  margin: 0;
  padding: 0;
}

如何制作,以便在使用给定库中的组件时,样式也被拉到它???

【问题讨论】:

    标签: javascript css reactjs webpack


    【解决方案1】:

    Webpack 中的加载器是从右到左评估的。在您的配置中,评估顺序是“css-loader”、MiniCssExtractPlugin.loader,最后是“style-loader”。但 'style-loader' 只将样式注入 DOM。您需要 MiniCssExtractPlugin.loader 成为“使用”数组中的第一个元素。见下文...

    { 
      test: /\.css$/, 
      use: [ MiniCssExtractPlugin.loader, 'css-loader' ] 
    }
    

    此外,您可以告诉 webpack 在生产期间使用 MiniCssExtractPlugin.loader,而在其他时间使用 'style-loader'。

    const isProduction = process.env.NODE_ENV == 'production';
    const stylesHandler = isProduction ? MiniCssExtractPlugin.loader : 'style-loader';
    
    ...other config
    
    { 
      test: /\.css$/, 
      use: [ stylesHandler, 'css-loader' ] 
    }
    

    在你的 package.json 脚本中,

    "build": "webpack --mode=production --node-env=production"
    

    【讨论】:

      猜你喜欢
      • 2011-12-30
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 2014-10-22
      • 2023-03-18
      • 1970-01-01
      • 2011-08-02
      • 2021-12-21
      相关资源
      最近更新 更多