You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Webpack中加载单个CSS文件而非node_modules中的多个文件

Target Only a Specific CSS File in node_modules with Webpack

Alright, let's tweak your webpack config to stop loading every .css file in node_modules and only target that specific 123.css from your package. Here's how you can do it:

Solution 1: Pinpoint the Exact File with include

Modify your module rule to include only the precise path of the CSS file you need. This ensures webpack only processes that one file and ignores all others in node_modules.

module: {
  rules: [
    {
      test: /\.css$/i,
      use: ["css-loader"],
      // Match the exact file path (use forward slashes for cross-platform compatibility)
      include: /node_modules\/package_name\/dist\/style\/123\.css$/
    }
  ]
}

Solution 2: Split Rules for Project CSS and Targeted Node Module CSS

If you also need to process CSS files from your own project (not just the node_modules one), split the rules to avoid conflicts:

module: {
  rules: [
    // Handle CSS files in your project root
    {
      test: /\.css$/i,
      use: ["css-loader"],
      exclude: /node_modules/
    },
    // Only handle the specific CSS file from the target package
    {
      test: /\.css$/i,
      use: ["css-loader"],
      include: /node_modules\/package_name\/dist\/style\/123\.css$/
    }
  ]
}

Quick Tips:

  • The include regex uses forward slashes (/) instead of backslashes to work seamlessly across Windows, macOS, and Linux.
  • We escape the dot in 123.css with \. because dots have special meaning in regular expressions.
  • This approach keeps your bundle size smaller by only bundling the exact CSS you need, and avoids unintended styles from other packages sneaking in.

内容的提问来源于stack exchange,提问作者Nilesh Butani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:53:23