如何在反应组件中导入一个css文件? [英] How to import a css file in a react component?

查看:119
本文介绍了如何在反应组件中导入一个css文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我想将CSS文件导入到反应组件中。我试过以下内容:

 从../../../public/styles/disabledLink导入disabledLink ; 

但是错误显示了我:


未找到模块:错误:无法解析文件或目录../../../public/styles/disabledLink in c:\ Users \User\Documents\ pizza-app \client\src\components
@ ./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


感谢您的任何意见!

css-loader 时使用wepback创建bundle。



安装它:

  npm install css-loader --save -dev 

然后将它添加到您的webpack配置中的加载器中:

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

在此之后,您将能够在js中包含css文件。

As the title says, i want to import a CSS file into a react component. I've tried the following:

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

But error shows me this:

Module not found: Error: Cannot resolve 'file' or 'directory' ../../../public/styles/disabledLink in c:\Users\User\Documents\pizza-app\client\src\components @ ./client/src/components/ShoppingCartLink.js 19:20-66
Hash: 2d281bb98fe0a961f7c4
Version: webpack 1.13.2

The file is located in this path:

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

To me it seems like import is not looking up the correct path. I thought with ../../../ it would start to look up the path three folder layers above.

The file that should import the CSS file is located here:

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

Thanks for any input!

解决方案

You need to use css-loader when creating bundle with wepback.

Install it:

npm install css-loader --save-dev

And add it to loaders in your webpack configs:

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

After this, you will be able to include css files in js.

这篇关于如何在反应组件中导入一个css文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆