【问题标题】:Unable to import css in ReactJs application无法在 ReactJs 应用程序中导入 css
【发布时间】:2018-09-20 04:35:36
【问题描述】:

我正在尝试将 html 模板转换为 ReactJs 应用程序。

一切正常
<link rel="stylesheet" href="%PUBLIC_URL%/css/styles-merged.css">

public\index.html 文件中,但是当我将style.min.css 文件从public\css folder 移动到src\index.js 时,它不起作用。我确信我犯了一个新手错误。我究竟做错了什么?

文件结构

public
   index.html
src
   index.js
   app.js 
   css
      style.min.css
   fonts
      glyphicons-halflings-regular.eot

错误:

./src/index.js Module not found: Can't resolve 'css/style.min.css' in 'c:\projects\sample\src'

public\index.html 文件:

<!DOCTYPE html>
<html lang="en">
  <head>
<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <!--<link rel="stylesheet" href="%PUBLIC_URL%/css/styles-merged.css">-->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  </head>  
  <body>
    <div id="root"></div>
  </body>
</html>

src\index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

import 'css/style.min.css';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

【问题讨论】:

    标签: javascript html css reactjs create-react-app


    【解决方案1】:
    import './css/style.min.css'
    

    您必须为要导入的模块提供相对路径,该路径位于相对目录中(此处位于src 内)

    当你这样做时

    import 'css/style.min.css'
    

    它会尝试在node_modules 目录中查找该模块。这是因为它不存在,你得到了

    找不到模块:无法解析 'c:\projects\sample\src' 中的 'css/style.min.css'

    【讨论】:

    • 我现在收到“未找到模块:无法解析 'c:\projects\sample\src\css' 中的 '../fonts/glyphicons-halflings-regular.eot'。 css文件是指src:url(../fonts/glyphicons-halflings-regular.eot)。这不应该基于css文件到字体文件的相对路径吗?
    • 你得到这个是因为获取该字体的相对 url 在你的 css 文件中是错误的。尝试找出该资源的相对路径 ./ 将从同一目录中获取资源 ../ 将进入一个目录。 ../../ 将上升两个目录。我知道这是因为您将style.min.css 移到了一个目录下。您可能需要在开头添加../
    猜你喜欢
    • 2018-09-30
    • 2018-05-03
    • 2021-09-03
    • 2014-06-22
    • 2018-11-10
    • 1970-01-01
    • 2012-04-19
    • 2013-05-17
    • 2017-09-17
    相关资源
    最近更新 更多