如何在不eject的create-react-app 2.0中实现Sass/Scss绝对路径导入?
Absolutely! You can set up absolute path imports for your Sass files without ejecting your CRA project—react-app-rewired is exactly the right tool for this job, paired with customize-cra to simplify config tweaks. Here's a step-by-step guide:
Step 1: Install Required Dependencies
First, install the dev dependencies you'll need:
npm install react-app-rewired customize-cra --save-dev # Or if you use Yarn yarn add react-app-rewired customize-cra --dev
Note: If you haven't already installed node-sass, you'll want to add that too since CRA's Sass support requires it.
Step 2: Update Your package.json Scripts
Replace the default react-scripts commands with react-app-rewired in your package.json:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" // Leave eject as-is just in case }
Step 3: Create a Config Override File
In your project's root directory (same level as package.json), create a file named config-overrides.js with this code:
const { override, addSassLoader } = require('customize-cra'); const path = require('path'); module.exports = override( addSassLoader({ includePaths: [path.resolve(__dirname, 'src')] }) );
This tells sass-loader to look for Sass files starting from your src directory. So if your styles/variables/_variables.scss is inside src, you can now import it like this:
@import "styles/variables/_variables.scss";
Optional: Adjust Paths If Needed
If your styles live in a different directory (not directly under src), just update the path in includePaths to point to that folder's absolute path. For example, if your styles are at the project root:
includePaths: [path.resolve(__dirname)]
内容的提问来源于stack exchange,提问作者Alex G

