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

如何在不eject的create-react-app 2.0中实现Sass/Scss绝对路径导入?

How to Use Absolute Imports for Sass in Create React App 2.x Without Ejecting

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:08:23