programing

React 컴포넌트에 CSS 파일을 Import하는 방법

lastcode 2023. 3. 28. 21:50
반응형

React 컴포넌트에 CSS 파일을 Import하는 방법

리액트 컴포넌트에 CSS 파일을 Import하고 싶다.

해봤어요import disabledLink from "../../../public/styles/disabledLink";아래의 에러가 표시됩니다.

모듈을 찾을 수 없습니다.오류: c:\Users\User\Documents\pizza-app\client\src\components@ . / client / src / Components / ShoppingCartLink . js 19 : 20 - 66 - HashCartLink : 2 . 28bbb 1 .

C:\Users\User\Documents\pizza-app\client\public\styles\disabledLink.css로딩하려는 CSS 파일의 위치입니다.

저는 Import가 올바른 경로를 찾지 못하고 있는 것 같습니다.

나는 생각했다../../../세 개의 폴더 레이어 위의 경로를 찾기 시작합니다.

C:\Users\User\Documents\pizza-app\client\src\components\ShoppingCartLink.js는 CSS 파일을 Import하는 파일의 위치입니다.

제가 무엇을 잘못하고 있으며 어떻게 고칠 수 있을까요?

다음 작업을 수행할 필요가 없는 경우 이름을 붙일 필요도 없습니다.

예.

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

자세한 예는 여기를 참조하십시오(JSX Live 컴파일러를 리액트 컴포넌트로 빌드).

웹 팩을 사용하여 번들을 작성할 때는 css-loader를 사용해야 합니다.

인스톨:

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 파일을 Import하여 CSS 규칙을 출력합니다.<head />를 참조해 주세요.

  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';

CSS 모듈을 사용하면 서로 다른 파일에서 동일한 CSS 클래스 이름을 사용하여 이름 충돌에 대해 걱정할 필요가 없습니다.

button.module.css

.error {
  background-color: red;
}

another-stylesheet.css

.error {
  color: red;
}

Button.js

import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
  render() {
    // reference as a js object
    return <button className={styles.error}>Error Button</button>;
  }
}

위의 솔루션은 완전히 변경되어 폐지되었습니다.CSS 모듈을 사용하는 경우(css-loader를 Import한 것으로 가정함)에 대한 해답을 오랫동안 찾고 있었는데, 결국 찾았습니다.새 버전에서는 기본 웹 팩 로더가 크게 다릅니다.

웹 팩에서 cssRegex로 시작하는 부품을 찾아서 이 부품으로 교체해야 합니다.

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

css 파일이 Import 하는 폴더와 같은 폴더에 있는 경우 단순하게 이 작업을 수행할 수 있습니다.

'.styles.css' Import'

css 파일이 파일이 있는 곳을 탐색하여 다음과 같이 사용하는 컴포넌트에서 멀리 떨어져 있는 경우

'../mainstyles/styles.css' 가져오기

스타일시트 전체를 묶지 않고 스타일시트에서 컴포넌트에 몇 가지 스타일만 삽입하고 싶은 경우에는 https://github.com/glortho/styled-import을 추천합니다.예를 들어 다음과 같습니다.

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

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

메모: 저는 이 lib의 저자이며 스타일 및 CSS 모듈의 대량 Import가 최선 또는 가장 실행 가능한 솔루션이 아닌 경우를 위해 이 lib를 구축했습니다.

필요한 모듈을 사용할 수도 있습니다.

require('./componentName.css');
const React = require('react');
  1. 스타일 로더 및 CSS 로더 설치:

    npm install --save-dev style-loader
    npm install --save-dev css-loader
    
  2. 웹 팩 구성

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

extract-css-chunks-webpack-plugin 및 css-loader loader 작업을 사용하여 다음을 참조하십시오.

webpack.config.js Import extract-css-chunks-webpack-plugin

const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');

webpack.config.js css 규칙을 추가하여 먼저 css Chunks를 추출한 후 css 로더 css-loader에 의해 html 문서에 삽입되고 css-loader 및 extract-css-chunks-web-pack-plugin이 패키지에 포함되어 있는지 확인합니다.json Deviences

rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: ExtractCssChunks.loader,
          },
          'css-loader',
        ],
      }
]

webpack.config.js 플러그인 인스턴스 만들기

plugins: [
    new ExtractCssChunks({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css'
    })
  ]

이제 css Import가 가능합니다.그리고 index.tsx와 같은 tsx 파일에서는 Import를 사용할 수 있습니다.Tree.css에는 다음과 같은 css 규칙이 포함되어 있습니다.

body {
    background: red;
}

내 앱은 타이프스크립트를 사용하고 있고, 이것은 나에게 효과가 있습니다.출처 레포(https://github.com/nickjohngray/staticbackeditor)를 확인해 주세요.

를 가져오면 됩니다..css.jsx 파일

예를 들면 다음과 같습니다.

import Content from '../content/content.jsx';

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

반응형