1 React doesn't build/run :(((
I was kinda stumped by this because I only ran yarn and yarn start, but this guy reminded me that node 17 is not a stable version :)
You can see that after that error messages, there's an indication that it's Node.js 17.0.1.
Just run the following do downgrade node:
brew uninstall --ignore-dependencies node
brew install node@16
brew link node@16
Then you will see successful deployment. Fewf!
2 Link React to Spring
It only became very apparent today how intuitive the linking process is between React and Spring. Essentailly, you want to get React's static files (html, js, css) from `yarn build`, and put it into the directory that Spring can find.
2.1 Make Spring application return index.html at GET /
FIrstly, create a controller (src/main/java/HomeController.java)
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping(value = "/")
public String index() {
return "index";
}
}
When you run Spring application, it will serve a page called 'index.html' when you enter `<domain>/' in the url. So if we just run spring application on port 8080, opening `localhost:8080/`will return index.html file.
2.2 Build React and move the files
In my case, I've created a react app at src/main/js. All the following terminal commands will be assuming that the current directory of the terminal is set to src/main/js.
Steps:
1. Run build to generate static files (html, css, js)
yarn build
2. Move all the static files to appropriate folders.
cp build/index.html ../resources/templates
mkdir -p ../resources/static/
cp -r build/static ../resources/static/static
Important to note:
index.html file should be located in src/main/resources/templates/index.html for HomeController.java to find index html file and return. Any static js/css files that index.html uses will be referenced with src/main/resources/static as a root.
For example, here's one reference to js script from index.html:
This actually means 2.6358e8ba.chunk.js should be located at src/main/resources/static/static/js/2.6358e8ba.chunk.js, for the reason that the root directory of the reference is src/main/resources/static. It's not a typo that I put 'static/static' as part of the location of 2.6358e8ba.chunk.js.
2.3 Run the Spring application, and see that index.html (generated by React) is served!
That's it! Just run the application - in my case the main entrypoint for Spring application is:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
And it is currrently configured to run at localhost port 8080.
Here's your familiar create-react-app:
The directory structure is as follows:
'2021 > November 2021' 카테고리의 다른 글
Vim with react & vscode! (0) | 2021.11.21 |
---|