【发布时间】:2020-02-08 11:37:22
【问题描述】:
我是 React 的初学者,我无法弄清楚为什么 css 在我的项目中不起作用。 我知道在 React 中我们不直接使用 CSS,而是通过使用 webpack 和 babel 将其解释和理解为 JavaScript。
我尝试了什么? 我认为更改我的 webpack.config.js 文件会起作用,但我不确定在哪里进行更改以及更改什么。我关注了 StackOverflow 中的一些线程,这些线程对在项目中加载 CSS 模块进行了更改。但我不确定是否实现它,因为我的 webpack.config.js 似乎默认已经有 css 模块,我相信我的原因是我有 react-scripts v3.3,默认情况下我们有 CSS 模块。
我的 react-scripts 版本 - 3.3。 此外,我在导入该组件 css 文件时使用命名约定作为 ComponentName.css 和相同。 我没有使用 ComponentName.modules.css 文件命名。 我不确定我是否在项目的一个主文件中遗漏了一些 css/bootstrap 链接引用。请建议,如果我们在 Index.js 之类的地方这样做。 这是我的 -
webpack.config.js 文件:
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
}),
},
【问题讨论】:
-
命名 CSS 文件是不够的,您还需要在组件中导入它们:
import './ComponentName.css';就足够了。 -
你是如何将你的 css 导入到你的 react 组件中的?
-
我也在我的组件中导入它们。
import classes from './ComponentName.css';我将它们用作<div className={classes.Particularclass}></div> -
你有没有想过这个问题?现在处理类似的问题,但使用 Vite 而不是 Webpack
标签: javascript css reactjs webpack css-modules