code

반응 구성 요소에서 CSS 파일을 가져 오는 방법은 무엇입니까?

codestyles 2020. 12. 6. 21:33
반응형

반응 구성 요소에서 CSS 파일을 가져 오는 방법은 무엇입니까?


제목에서 알 수 있듯이 CSS 파일을 반응 구성 요소로 가져오고 싶습니다. 나는 다음을 시도했다 :

import disabledLink from "../../../public/styles/disabledLink";

그러나 오류는 이것을 보여줍니다.

모듈을 찾을 수 없음 : 오류 : c : \ Users \ User \ Documents \ pizza-app \ client \ src \ components @에서 'file'또는 'directory'../../../public/styles/disabledLink를 확인할 수 없습니다. /client/src/components/ShoppingCartLink.js 19 : 20-66
Hash : 2d281bb98fe0a961f7c4
버전 : webpack 1.13.2

파일은 다음 경로에 있습니다.

C : \ Users \ User \ Documents \ pizza-app \ client \ public \ styles \ disabledLink.css

나에게 가져 오기가 올바른 경로를 찾지 못하는 것 같습니다. 나는 ../../../그것으로 위의 세 폴더 레이어 경로를 찾기 시작할 것이라고 생각 했습니다.

CSS 파일을 가져와야하는 파일은 다음 위치에 있습니다.

C : \ Users \ User \ Documents \ pizza-app \ client \ src \ components \ ShoppingCartLink.js

입력 해 주셔서 감사합니다!


다음을 수행 할 필요가 없으면 이름을 지정할 필요도 없습니다.

예 :

import React from 'react';
import './App.css';

여기에서 전체 예제를 참조하십시오 ( React Component로 JSX Live Compiler 빌드 ).


당신은 사용할 필요가 CSS-로더를 wepback로 번들을 만들 때.

그것을 설치하십시오 :

npm install css-loader --save-dev

웹팩 구성의 로더에 추가하십시오.

module.exports = {
  module: {
    loaders: [
      { test: /\.css$/, loader: "style-loader!css-loader" },
      // ...
    ]
  }
};

그런 다음 js에 css 파일을 포함 할 수 있습니다.


CSS 모듈을 사용하는 것이 좋습니다.

반응

import React from 'react';
import styles from './table.css';

export default class Table extends React.Component {
    render () {
        return <div className={styles.table}>
            <div className={styles.row}>
                <div className={styles.cell}>A0</div>
                <div className={styles.cell}>B0</div>
            </div>
        </div>;
    }
}

컴포넌트 렌더링 :

<div class="table__table___32osj">
    <div class="table__row___2w27N">
        <div class="table__cell___2w27N">A0</div>
        <div class="table__cell___1oVw5">B0</div>
    </div>
</div>

다음은 React 컴포넌트에서 외부 CSS 파일을 가져오고 <head />웹 사이트 의 CSS 규칙을 출력합니다 .

  1. 스타일 로더CSS 로더 설치 :
npm install --save-dev style-loader
npm install --save-dev css-loader
  1. webpack.config.js에서 :
module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
            }
        ]
    }
}
  1. 구성 요소 파일에서 :
import './path/to/file.css';

  1. Install Style Loader and CSS Loader: npm install --save-dev style-loader npm install --save-dev css-loader

  2. Configure webpack

module: { loaders: [ { test: /.css$/, loader: 'style-loader' }, { test: /.css$/, loader: 'css-loader', query: { modules: true, localIdentName: '[name][local]_[hash:base64:5]' } } ] }


In cases where you just want to inject some styles from a stylesheet into a component without bundling in the whole stylesheet I recommend https://github.com/glortho/styled-import. For example:

const btnStyle = styledImport.react('../App.css', '.button')

// btnStyle is now { color: 'blue' } or whatever other rules you have in `.button`.

NOTE: I am the author of this lib, and I built it for cases where mass imports of styles and CSS modules are not the best or most viable solution.


You can also use the required module.

require('./componentName.css');
const React = require('react');

The solutions above are completely changed and deprecated. If you want to use css modules(assuming you imported css-loaders) and I have been trying to find an answer for this for such a long time and finally did. The default webpack loader is quite different in new version.

in your webpack, you need to find a part starting with cssRegex and replace it with this;

{
  test: cssRegex,
  exclude: cssModuleRegex,
  use: getStyleLoaders({
      importLoaders: 1,
      modules: true,
      localIdentName: '[name]__[local]__[hash:base64:5]'
  }),
}

참고URL : https://stackoverflow.com/questions/39853646/how-to-import-a-css-file-in-a-react-component

반응형