如何在基于Create React App的React应用.SASS文件中导入Compass?
Hey there! Let's get that Compass import working smoothly in your Create React App project. You've already got the right dependencies installed, so we just need to tweak the build configuration to make Sass recognize Compass. Here's how to do it:
Option 1: Use react-app-rewired (No Eject Required)
This is the recommended approach since it lets you customize the build config without ejecting (which is irreversible).
Install two more dev dependencies to help with config overrides:
npm install react-app-rewired customize-cra --save-devCreate a
config-overrides.jsfile in your project root directory, and add this code to configure the Sass loader with Compass support:const { override, addSassLoader } = require('customize-cra'); const compassImporter = require('compass-importer'); module.exports = override( addSassLoader({ sassOptions: { importer: compassImporter(), includePaths: require('react-compass').includePaths } }) );Update your
package.jsonscripts to usereact-app-rewiredinstead ofreact-scripts:"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }Now you can import Compass modules directly in your
.sassfile! For example:# Import specific Compass modules @import "compass/css3" @import "compass/reset" # Or import the entire Compass library @import "compass"
Option 2: Eject Your Create React App (Irreversible)
If you don't mind ejecting and taking full control of the build config, follow these steps:
Run the eject command (this can't be undone!):
npm run ejectOpen
config/webpack.config.jsand find the section wheresass-loaderis configured. Look for theoptionsobject undersass-loader, and add the Compass importer and include paths:{ loader: require.resolve('sass-loader'), options: { sassOptions: { importer: require('compass-importer')(), includePaths: require('react-compass').includePaths, // Keep any existing options here }, }, }Save the file, restart your dev server, and you'll be able to import Compass in your
.sassfiles just like in the first option.
Quick Notes
- Make sure your Sass files use the correct
.sassextension (not.scss) since you mentioned using the indented syntax from the CodePen snippet. - If you're using
node-sass-chokidarto watch and compile Sass files manually, double-check that its configuration also includes the Compass include paths to avoid build errors.
内容的提问来源于stack exchange,提问作者RebeccaK375

