简体   繁体   English

如何导入 scss 文件并在 React 应用程序中全局使用它们?

[英]How to import scss files and use them globally in a React application?

I have my React application structures like this:我有这样的 React 应用程序结构:

-src
|-components
 |-Card.js
 |-Card.scss
 |-Navbar.js
 |-Navbar.scss
|-styles
 |-_mixins.scss
 |-_variables.scss
|-App.js
|-App.scss

I use node-sass so for component-x I just need to import component-x.scss to apply the scss file.我使用node-sass所以对于 component-x 我只需要import component-x.scss来应用 scss 文件。 However I have the _mixins.scss and _variables.scss which I need to use on everywhere, I cannot import them in each scss file.但是我有需要在任何地方使用的_mixins.scss_variables.scss ,我无法在每个scss文件中import它们。 How can I import these files globally so I could use them anywhere I want?如何在全球范围内导入这些文件,以便可以在任何我想要的地方使用它们?

Create a main.scss and import all inside!创建一个main.scss并在里面全部导入!

There is an example with your files:您的文件有一个示例:

/********************************SASS MAIN***********************************/
//COMPONENTS
@import "components/card";
@import "components/navbar";

//STYLES
@import "styles/mixins";
@import "styles/variables";

Then in your App.js just import 'main.scss'然后在你的 App.js 中只import 'main.scss'

more info about import in sass here有关在sass中导入的更多信息

you can use customize-cra with react-app-rewired and in you config-overrides.js你可以在react-app-rewiredconfig-overrides.js中使用customize-cra


const { override, adjustStyleLoaders } = require("customize-cra");
const path = require("path");

module.exports = override(
  adjustStyleLoaders((loader) => {
    loader.use[1].options.additionalData = `@import "./src/assets/scss/_variables.scss";`;
  })
);

and change your package.json scripts into并将您的 package.json 脚本更改为

  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM