Program Club

Django와 ReactJS-실제 사용

proclub 2020. 10. 19. 13:03
반응형

Django와 ReactJS-실제 사용


나는 React를 조금 엉망으로 만들고 있었고 꽤 좋아했습니다. Angular (| 필터를 사용한 ng-repeat는 귀중함)보다 훨씬 장황하지만 괜찮습니다.

저를 괴롭히는 것은 Django 템플릿과 함께 React를 사용하는 방법입니다. 모든 자바 스크립트를 "HTML"마크 업과 함께 템플릿에 넣어야합니다.

Angular 구현은 매우 원활했습니다. 템플릿 / django 양식 클래스에 몇 가지 속성을 넣은 다음 별도의 파일에 javascript를 작성했습니다. 해당 파일을 포함하면 완료됩니다.

반응을 "사용"하는 방법? 올바른 방법은 무엇입니까?

미리 감사드립니다!


Django 템플릿과 함께 React를 사용하고 싶기 때문에 React 코드가 페이지의 특정 부분에만 영향을 미칠 것이라고 가정합니다. 다음 설명은 이러한 가정을 기반으로 작성되었습니다.

우선, 템플릿에 모든 JS 코드를 넣을 필요가 없습니다. 사실 그것은 엉망이 될 것입니다.

Webpack을 사용하여 별도의 JS 기반 빌드 프로세스 생성 할 수 있습니다 ( 이 howto 확인 ). 이를 통해 클라이언트 측 코드의 기능이 향상되어 브라우저에서 CommonJS 모듈을 사용할 수 있으며, React를 포함하여 npm에서 직접 가져올 수 있습니다 .

Webpack은 <script>평상시처럼 태그를 통해 Django 템플릿에 포함해야하는 번들 (또는 애플리케이션의 특성 및 Webpack 구성에 따라 여러 번들)을 생성합니다 .

이제 React.render()기존 페이지 레이아웃의 어딘가에 React 애플리케이션을 렌더링 하도록 호출 해야 합니다. 특정 ID / 클래스 이름이있는 빈 HTML 요소를 애플리케이션의 마운트 지점으로 사용해야합니다.

그러나 여기에주의해야합니다. 브라우저 나 Django 템플릿에서 CommonJS 모듈에 직접 액세스 할 수 없습니다. 그래서 당신도

  • 개체에 React앱을 노출 window하거나
  • 앱 초기화를 처리하고 해당 메서드를 window객체에 노출하는 글루 코드로 모듈을 만듭니다 .

어떤 경우 든 템플릿에서 직접 초기화 코드를 호출해야합니다 ( 글루 코드 예제앱 초기화 호출 확인 ).

이 초기화 단계에서는 Django 템플릿에서 사용 가능한 변수를 JS 코드에 전달할 수도 있습니다.

최종 Django 템플릿은 다음과 같습니다.

{% load staticfiles %}
{% extends 'base.html' %}

{% block scripts %}
<script type="text/javascript" src="{% static 'path/to/app.bundle.js' %}"></script>
<script type="text/javascript">
  // Initialization glue code
  window.MyApp.init({el: '.app-mountpoint'});
</script>
{% endblock %}

{% block content %}
<!-- Your template contents -->

<!-- The mount point of your app -->
<div class="app-mountpoint" />
{% endblock %}

그리고 접착제 코드 :

var React = require('react');

var MyAppComponent = require('MyAppComponent');


window.MyApp = {

  init: function (opts) {
    var mountPoint = document.querySelector(opts.el);

    React.render(<MyAppComponent />, mountPoint);
  }

};

이 모든 것이 처음에는 압도적으로 들릴 수 있다는 것을 알고 있지만 (Angular로 수행 한 몇 가지 단계에 비해 훨씬 더 많음), 장기적으로 보면 효과가 있다고 믿습니다.

요약하자면 :

  1. 별도의 JS 파일에 React 코드 작성
  2. Webpack (CommonJS 모듈 활용)을 사용하여 React 코드 번들링
  3. Django 템플릿에 번들 포함
  4. Django 템플릿에서 글루 코드를 사용하여 React 코드 렌더링

프런트 엔드와 백엔드를 두 개의 서로 다른 독립된 엔티티로 간주한다면 어떻게 될까요? 다음을 의미합니다.

  1. Django는 API 여야하며 json 데이터로 응답해야합니다.
  2. 프런트 엔드는 nginx에서 제공하는 정적 파일이어야합니다.
  3. You may have to deal with CORS in order to allow communication between the two. One option would be to allow preflight requests from your frontend and the other option would be to set up an nginx proxy. This is a separate issue and you should search for it if you need more details.

I think this architecture allows you to keep things separated and not deal with their integration. Things are already too complicated on the frontend/React ecosystem so I think simplicity of config has to be taken into account.

I would also be interested to find out how a deployment process would look for this architecture (what tools to use?), so please add comments if you have suggestions and I'll update the response accordingly to supply useful info for future readers.


I implemented something similar to what you are asking. My front end is entirely on reactjs which is compiled using webpack and my templates are created in django.

So I do following:-

  1. Use react-router and react to create .jsx/.js code.
  2. Compile using webpack.
  3. Use django-webpack

So django-webpack works really nice and helps you isolated you compilation outside of django to get thinks working in a nice and scalable way.

참고URL : https://stackoverflow.com/questions/28610372/reactjs-with-django-real-usage

반응형