3

I am trying to learn React and I use "create-react-app". I now have an issue that I find very strange and am not able to solve.

I have a map-structure like this:

   administratie
   └─ public
      └─ static
         └─ img
         └─ js
   └─ src
      └─ content

In my content I have a Content.js that looks like this:

import React, { Component } from "react";

import "./Mut.css";
import { format } from "./static/js/date.js"; // Error

class Mut extends Component {
  constructor(props) {
    super(props);
    this.state = {
      datum: ""
    };
  }

  componentDidMount() {
    let today = format(new Date());
    this.setState({
      datum: today
    });
  }

  handleChange(event) {}

  render() {
    return (
      <main>
        <img src="./static/img/administratie-logo.png" alt="logo" />  // Is rendered as it should
      </main>
    );
  }
}

export default Mut;

On line 4 I import a .js-file from the static folder. On line 26 I show an image from the static folder. Now the image is shown nicely but the import gives me the error:

./src/content/Mut.js
Module not found: Can't resolve './static/js/date.js' in 'C:\react-projects\administratie\src\content'

The date.js file looks like this:

export function format(d) {
  let day = d.getDate().toString();
  if (day < 10) day = "0" + day;

  let month = (d.getMonth() + 1).toString();
  if (month.length === 1) month = "0" + month;

  const year = d.getFullYear().toString();

  return day + "-" + month + "-" + year;
}

Any insight is hugely appreciated!

johannes
  • 1,270
  • 12
  • 19

1 Answers1

3

The URL inside <img> tag is resolved at run time, by the browser. That is why, the image loads fine.

However, the Javascript file specified in the import statement will be resolved at the compilation time.

React looks for modules in the 'src' and node_modules folders only.

The failing import statement is:

import { format } from "./static/js/date.js"; // Error

React is throwing the error because /static/js/date.js does not exist in either 'src' or 'node_modules'

To make the code work, the date.js file can be copied to a location under the 'src' folder.

(node_modules is for the dependencies downloaded through 'npm install')

Gopinath
  • 4,066
  • 1
  • 14
  • 16