如何在create-react-app中启用CSS modules?react-scripts 1.1.4版本失效
Hey there! Let's break down why the .module.css trick isn't working for you, and walk through the solutions to get CSS Modules up and running.
Why the .module.css method fails with react-scripts 1.1.4
Dan Abramov's tweet about enabling CSS Modules via
.module.cssfiles refers to a feature that was natively added in create-react-app v2.0.0 and later. Your current version,react-scripts 1.1.4, is part of the v1.x series which doesn't support this out-of-the-box—this is exactly why renaming your stylesheets isn't having any effect.
Solution 1: Upgrade react-scripts to v2.0.0+ (Recommended)
This is the simplest and most future-proof approach, as it lets you use the native CSS Modules support Dan mentioned:
- Run the upgrade command in your project directory:
# Using npm npm install react-scripts@latest --save # Using yarn yarn add react-scripts@latest - Rename your stylesheet files to follow the
[filename].module.csspattern (e.g.,Button.module.cssinstead ofButton.css) - Import and use the styles in your React components like this:
import styles from './Button.module.css'; function Button() { return <button className={styles.button}>Click Me</button>; }
Solution 2: Enable CSS Modules in react-scripts 1.1.4 (Without Upgrading)
If you can't upgrade for some reason, you can use react-app-rewired to modify the CRA config without ejecting:
- Install the required dev dependencies:
# Using npm npm install react-app-rewired react-app-rewire-css-modules --save-dev # Using yarn yarn add react-app-rewired react-app-rewire-css-modules --dev - Create a
config-overrides.jsfile in your project root with this content:const rewireCssModules = require('react-app-rewire-css-modules'); module.exports = function override(config, env) { config = rewireCssModules(config, env); return config; }; - Update your
package.jsonscripts to usereact-app-rewiredinstead of the default react-scripts:"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test --env=jsdom" } - Now you can use CSS Modules with your existing
.cssfiles—no need to rename them. Import and use styles like this:import styles from './Button.css'; function Button() { return <button className={styles.button}>Click Me</button>; }
内容的提问来源于stack exchange,提问作者Muhammad Saqib

