如何在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
includeregex uses forward slashes (/) instead of backslashes to work seamlessly across Windows, macOS, and Linux. - We escape the dot in
123.csswith\.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
相关产品推荐
相关产品推荐

