SlideShare a Scribd company logo
CREATING A FULL STACK WEB APP WITH
PYTHON, NPM, WEBPACK AND REACT
by Angela Branaes
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
THE STRUCTURE OF A WEB APP
➤ Separated into front and back end.
➤ Multiple technologies.
➤ Front end is:
➤ Look and feel.
➤ User interaction.
➤ Back end is:
➤ Long running operations.
➤ Data, and data processing.
➤ Application logic.
INITIAL PROJECT SETUP
➤ Create the following directory structure
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
└── js/
$ cd fullstack_template/static
WE’RE GOING TO NEED A JAVASCRIPT PACKAGE MANAGER
➤ Using a package manager makes it painless to:

➤ Keep your project dependencies up to date.

➤ Fetch and install new packages.

➤ Similar to brew, pip, pacman etc.
NPM
NPM = NODE PACKAGE MANAGER
➤ Automatically included with Node.js

➤ Easy to use

➤ well documented

➤ nearly 500 000 packages available

➤ Initialise NPM:

$ npm init
➤ This creates a file called package.json
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
├── js/
└── package.json
THE PURPOSE OF PACKAGE.JSON
1. Keeps track of dependencies and versions.

2. Informs other developers about your project.

3. Makes installing, running and updating a project automatic and reproducible
THIS IS MY PACKAGE.JSON
{
"name": "FullStackTemplate",
"version": "1.0.0",
"description": "Fullstack Template",
"main": "index.jsx",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
},
"keywords": [
"python",
"react",
"npm",
"webpack"
],
"author": "Angela Branaes",
"license": "MIT",
"devDependencies": {
"webpack": "^3.0.0"
}
}
WHY WE NEED A MODULE BUNDLER
➤ Minimises the number of <script> tags in your HTML
➤ This means faster loading, and less hassle.
➤ Don’t need to worry about bundle import ordering!
➤ Don’t have to use globals or namespacing.
➤ Lazy module loading.
➤ We will be using Webpack.
WEBPACK
WEBPACK
➤ Only understands JavaScript.
➤ Everything else needs a loader or plugin.
➤ Everything is a module.
➤ You can require() JavaScript, React, CSS or images.
➤ Creates a dependency tree of all your required modules, and packages those into
bundles.
➤ Easy to get started with, if you only need JavaScript.
➤ Minor learning curve for css/less and image loading.
➤ Lets you split your bundles and load them asynchronously and lazily.
➤ Integrates seamlessly with npm.
INSTALL & CONFIGURE WEBPACK
➤ Install webpack:
$ npm i webpack --save-dev
➤ Add a file named webpack.config.js:
const webpack = require(‘webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
};
module.exports = config;
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
├── js/
├── package.json
└── webpack.config.js
SINGLE VS MULTI PAGE APPLICATIONS
➤ I mostly use Webpack for single page applications.
➤ You can also use webpack for multi page applications:
entry: {

“indexPage”: __dirname + “js/index.jsx”,

“aboutPage”: __dirname + “js/about.jsx”
},
output: {
path: __dirname + “/dist”,

filename: “[name].js” //e.g. aboutPage.js
}
LET’S DISPLAY AN ALERT!
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
│ └── bundle.js
├── images/
├── js/
│ └── index.jsx
├── index.html
├── package.json
└── webpack.config.js
CREATE INDEX.HTML
➤ A really simple index.html is all you need.
➤ The index.html just loads your JavaScript bundle
<body>
<div id="content" />
<script src="dist/bundle.js" type=“text/javascript”>
</script>
</body>
➤ All the layout and behaviour live in the JS/React files!
CREATE INDEX.JSX
➤ Just 1 line of Plain Old JavaScript
alert(“Hello World!”);
BUILDING YOUR APPLICATION
➤ Create run commands to simplify building your code.
➤ Run commands are just aliases.
➤ Example from my package.json:
“scripts": {
"watch": "webpack --progress -d --config webpack.config.js —watch"
}
➤ Makes the dev process more fluid.
➤ I always add the following:
➤ build
➤ dev-build
➤ watch
START THE WATCH COMMAND
➤ Any changes get built automatically
$ npm run watch
➤ Open index.html….
Creating a full stack web app with python, npm, webpack and react
CREATING A SIMPLE REACT APP
THE BENEFITS OF USING REACT
➤ Easy to build UIs composed of small, distinct components.
➤ Encourages design of reusable UI components.
➤ Easier to understand what’s going on when markup lives with the code (JSX).
➤ Automatic re-rendering of components on change.
➤ Easy to maintain.
INSTALL REACT
$ npm i react react-dom —save-dev
REACTIFY INDEX.JSX
import React from "react";
import ReactDOM from "react-dom";
import App from “./App";
ReactDOM.render(<App />, document.getElementById("content"));
ADD A REACT “APP” CLASS
➤ Remember to export your react classes!
// App.jsx
import React from “react”;
export default class App extends React.Component {
render () {
return <p> Hello React!</p>;
}
}
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
├── js/
│ ├── index.jsx
│ └── App.jsx
├── index.html
├── package.json
└── webpack.config.js
WHAT IS JSX?
➤ Syntax extension to JavaScript.
➤ Optimised on compilation, so faster than JavaScript.
➤ Statically typed and mostly type-safe. JavaScript is not.
➤ Lets you write HTML tags in your JavaScript functions:
<Hello name=“Rimini” />
instead of
React.createElement(Hello, {name: “Rimini}, null)
➤ Recognises upper-case element-types as written in React. E.g. <Hello />
➤ How do we make our browser understand JSX?
INTRODUCING BABEL
Write next-generation javascript right now!
Transform JSX to JS.
ADD BABEL
➤ Install Babel
➤ Add the Babel presets to the package.json:
“babel”: {
“presets”: [
“es2015”,
“react”
]
},
ADD A BABEL-LOADER RULE TO THE WEBPACK CONFIG:
module: {
rules: [
{
test: /.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
OPEN INDEX.HTML IN YOUR BROWSER
➤ This should now show the “Hello React” paragraph we added in our new React
App.jsx file.
Creating a full stack web app with python, npm, webpack and react
PYTHON FLASK SERVER
PYTHON
➤ Go to the server folder
➤ Ensure you’re in a Python virtualenv
$ mkvirtualenv fullstack
➤ Install Flask
(fullstack)$ pip install flask
➤ Create a file called server.py in the server folder
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
├── dist/
├── images/
├── js/
│ ├── index.jsx
│ └── App.jsx
├── index.html
├── package.json
└── webpack.config.js
SERVER.PY
from flask import Flask, render_template
app = Flask(__name__, static_folder=“../static/dist",
template_folder="../static")
@app.route("/")
def index():
return render_template("index.html")
@app.route("/hello")
def hello():
return "Hello World!”
if __name__ == "__main__":
app.run()
START THE SERVER
➤ Go to: http://localhost:5000/
$ python server.py
REQUEST INFO FROM THE SERVER
var $ = require(‘jquery');
getPythonHello() {
$.get(window.location.href + 'hello', (data) => {
console.log(data);
this.personaliseGreeting(data);
});
}
MAKE PYTHON DO SOMETHING MORE INTERESTING
➤ We call get_hello() whenever we hit the /hello endpoint
def get_hello():
greeting_list = ['Ciao', 'Hei', 'Salut', 'Hola', 'Hallo', 'Hej']
return random.choice(greeting_list)
SAY HI TO SOMEONE SPECIAL
➤ There should be a class for that!

➤ Change the App.jsx render method to the following:

render () {
return (
<PageHeader>
<div className='header-contents'>
<Hello name='Rimini' />
</div>
</PageHeader>
);
)
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
├── dist/
├── images/
├── js/
│ ├── index.jsx
│ ├── App.jsx
│ └── Hello.jsx
├── index.html
├── package.json
└── webpack.config.js
CREATE THE HELLO CLASS
export default class Hello extends React.Component {
constructor(props) {
super(props);
// greeting is now “Hello Rimini”
this.state = {greeting: 'Hello ' + this.props.name};
// This binding is necessary to make `this`
// work in the button callback
this.getPythonHello = this.getPythonHello.bind(this);
}
}
➤ Add this function to the Hello class:
➤ This will re-render the greeting on our website to a new one when called.
personaliseGreeting(greeting) {
this.setState({greeting: greeting + ' ' + this.props.name + '!'});
}
LET’S FINALLY RENDER OUR HELLO!
render () {
return (
<h1>{this.state.greeting}</h1>
<hr/>
<Button onClick={this.getPythonHello}>
Say Hello!
</Button>
);
}
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
CREATE A NICE LAYOUT WITH CSS
➤ Webpack ONLY understands JavaScript.
➤ Install the following loaders and plugins:
➤ style-loader
➤ css-loader
➤ extract-text-webpack-plugin
➤ Add a plugin to the webpack config:
plugins: [
new ExtractTextPlugin('styles.css'),
]
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
│ └── fullstack.css
├── dist/
│ ├── bundle.js
│ └── styles.css
├── images/
├── js/
│ ├── index.jsx
│ ├── App.jsx
│ └── Hello.jsx
├── index.html
├── package.json
└── webpack.config.js
➤ Add fullstack.css to the css folder
➤ Add a few css rules for our header
➤ require fullstack.css in App.jsx:
require(‘../css/fullstack.css');
➤ Add the bundled css to the index.html:
<link rel="stylesheet" href="dist/styles.css">
Creating a full stack web app with python, npm, webpack and react
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
│ └── fullstack.css
├── dist/
│ ├── bundle.js
│ └── styles.css
├── images/
│ └── header.png
├── js/
│ ├── index.jsx
│ ├── App.jsx
│ └── Hello.jsx
├── index.html
├── package.json
└── webpack.config.js
ADD A NICE BACKGROUND IMAGE
1. Add the file-loader loader
2. Add an image to your images/ folder
3. Set the image to be your header background in the fullstack.css file
background-image: url(‘../images/header.jpg’);
4. NOTE: you have to load the image in your React app for it to show up!
IN APP.JSX
import HeaderBackgroundImage from ‘../images/header.jpg’;
➤ Add this fn to your class:
addHeaderImg() {
let headerBg = new Image();
headerBg.src = HeaderBackgroundImage;
}
➤ And this to your render():
{this.addHeaderImg()}
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
THANK YOU! ANY QUESTIONS?
@angineering
@angineering - The code is on GitHub:
https://github.com/angineering/FullStackTemplate
@angineering - This talk is also a blogpost

More Related Content

What's hot

Vagrant crash course
Vagrant crash courseVagrant crash course
Vagrant crash course
Marcus Deglos
 
WPDay Bologna 2013
WPDay Bologna 2013WPDay Bologna 2013
WPDay Bologna 2013
Danilo Ercoli
 
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Acquia
 
Godefroid Chapelle Ajax With Plone 3 Kss Development Patterns
Godefroid Chapelle   Ajax With Plone 3   Kss Development PatternsGodefroid Chapelle   Ajax With Plone 3   Kss Development Patterns
Godefroid Chapelle Ajax With Plone 3 Kss Development Patterns
Vincenzo Barone
 
BPMS1
BPMS1BPMS1
Hitchhiker's guide to the front end development
Hitchhiker's guide to the front end developmentHitchhiker's guide to the front end development
Hitchhiker's guide to the front end development
정윤 김
 
Front end performance optimization
Front end performance optimizationFront end performance optimization
Front end performance optimization
Stevie T
 
Vagrant
VagrantVagrant
Front End Performance
Front End PerformanceFront End Performance
Front End Performance
Konstantin Käfer
 
GlassFish Embedded API
GlassFish Embedded APIGlassFish Embedded API
GlassFish Embedded API
Eduardo Pelegri-Llopart
 
Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))
Michele Orselli
 
Introduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & WebIntroduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & Web
JWORKS powered by Ordina
 
Vagrant for Virtualized Development
Vagrant for Virtualized DevelopmentVagrant for Virtualized Development
Vagrant for Virtualized Development
Adam Culp
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment Workflows
AOE
 
Front end performance tip
Front end performance tipFront end performance tip
Front end performance tip
Steve Yu
 
WebPagetest Power Users - Velocity 2014
WebPagetest Power Users - Velocity 2014WebPagetest Power Users - Velocity 2014
WebPagetest Power Users - Velocity 2014
Patrick Meenan
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
Edureka!
 
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
Hanoi MagentoMeetup
 
Single page apps with drupal 7
Single page apps with drupal 7Single page apps with drupal 7
Single page apps with drupal 7
Chris Tankersley
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and Maintenance
Jazkarta, Inc.
 

What's hot (20)

Vagrant crash course
Vagrant crash courseVagrant crash course
Vagrant crash course
 
WPDay Bologna 2013
WPDay Bologna 2013WPDay Bologna 2013
WPDay Bologna 2013
 
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
 
Godefroid Chapelle Ajax With Plone 3 Kss Development Patterns
Godefroid Chapelle   Ajax With Plone 3   Kss Development PatternsGodefroid Chapelle   Ajax With Plone 3   Kss Development Patterns
Godefroid Chapelle Ajax With Plone 3 Kss Development Patterns
 
BPMS1
BPMS1BPMS1
BPMS1
 
Hitchhiker's guide to the front end development
Hitchhiker's guide to the front end developmentHitchhiker's guide to the front end development
Hitchhiker's guide to the front end development
 
Front end performance optimization
Front end performance optimizationFront end performance optimization
Front end performance optimization
 
Vagrant
VagrantVagrant
Vagrant
 
Front End Performance
Front End PerformanceFront End Performance
Front End Performance
 
GlassFish Embedded API
GlassFish Embedded APIGlassFish Embedded API
GlassFish Embedded API
 
Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))Vagrant for real codemotion (moar tips! ;-))
Vagrant for real codemotion (moar tips! ;-))
 
Introduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & WebIntroduction to Webpack - Ordina JWorks - CC JS & Web
Introduction to Webpack - Ordina JWorks - CC JS & Web
 
Vagrant for Virtualized Development
Vagrant for Virtualized DevelopmentVagrant for Virtualized Development
Vagrant for Virtualized Development
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment Workflows
 
Front end performance tip
Front end performance tipFront end performance tip
Front end performance tip
 
WebPagetest Power Users - Velocity 2014
WebPagetest Power Users - Velocity 2014WebPagetest Power Users - Velocity 2014
WebPagetest Power Users - Velocity 2014
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
 
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
 
Single page apps with drupal 7
Single page apps with drupal 7Single page apps with drupal 7
Single page apps with drupal 7
 
Pyramid Deployment and Maintenance
Pyramid Deployment and MaintenancePyramid Deployment and Maintenance
Pyramid Deployment and Maintenance
 

Similar to Creating a full stack web app with python, npm, webpack and react

WEBPACK
WEBPACKWEBPACK
WEBPACK
home
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
David Gibbons
 
Webpack presentation
Webpack presentationWebpack presentation
Webpack presentation
RAHUL SHARMA
 
Improving build solutions dependency management with webpack
Improving build solutions  dependency management with webpackImproving build solutions  dependency management with webpack
Improving build solutions dependency management with webpack
NodeXperts
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
ValeriaCastillo71
 
Ultimate Survival - React-Native edition
Ultimate Survival - React-Native editionUltimate Survival - React-Native edition
Ultimate Survival - React-Native edition
Richard Radics
 
ReactJS Workflows
ReactJS WorkflowsReactJS Workflows
ReactJS Workflows
Cem Arguvanlı
 
Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
Vijay Shukla
 
Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014
Stéphane Bégaudeau
 
Magento 2 Development
Magento 2 DevelopmentMagento 2 Development
Magento 2 Development
Duke Dao
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
Stein Inge Morisbak
 
2019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 22019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 2
Larry Eichenbaum
 
Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014
Stéphane Bégaudeau
 
ReactJS software installation
ReactJS software installationReactJS software installation
ReactJS software installation
HopeTutors1
 
How to install ReactJS software
How to install ReactJS software How to install ReactJS software
How to install ReactJS software
VigneshVijay21
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
Stein Inge Morisbak
 
Learn react-js
Learn react-jsLearn react-js
Room with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.jsRoom with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.js
Zachary Klein
 
Getting Started with React v16
Getting Started with React v16Getting Started with React v16
Getting Started with React v16
Benny Neugebauer
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
Dalibor Gogic
 

Similar to Creating a full stack web app with python, npm, webpack and react (20)

WEBPACK
WEBPACKWEBPACK
WEBPACK
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
Webpack presentation
Webpack presentationWebpack presentation
Webpack presentation
 
Improving build solutions dependency management with webpack
Improving build solutions  dependency management with webpackImproving build solutions  dependency management with webpack
Improving build solutions dependency management with webpack
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
 
Ultimate Survival - React-Native edition
Ultimate Survival - React-Native editionUltimate Survival - React-Native edition
Ultimate Survival - React-Native edition
 
ReactJS Workflows
ReactJS WorkflowsReactJS Workflows
ReactJS Workflows
 
Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
 
Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014Modern Web Application Development Workflow - EclipseCon Europe 2014
Modern Web Application Development Workflow - EclipseCon Europe 2014
 
Magento 2 Development
Magento 2 DevelopmentMagento 2 Development
Magento 2 Development
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
 
2019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 22019 Chef InSpec Jumpstart Part 2 of 2
2019 Chef InSpec Jumpstart Part 2 of 2
 
Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014Modern Web Application Development Workflow - EclipseCon France 2014
Modern Web Application Development Workflow - EclipseCon France 2014
 
ReactJS software installation
ReactJS software installationReactJS software installation
ReactJS software installation
 
How to install ReactJS software
How to install ReactJS software How to install ReactJS software
How to install ReactJS software
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Room with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.jsRoom with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.js
 
Getting Started with React v16
Getting Started with React v16Getting Started with React v16
Getting Started with React v16
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
 

Recently uploaded

Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
Mitchell Marsh
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
ThousandEyes
 
Safe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work PermitsSafe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work Permits
sheqnetworkmarketing
 
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdfAWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
karim wahed
 
Splunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptxSplunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptx
sudsdeep
 
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
Hironori Washizaki
 
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
karim wahed
 
Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)
miso_uam
 
Development of Chatbot Using AI\ML Technologies
Development of Chatbot Using AI\ML TechnologiesDevelopment of Chatbot Using AI\ML Technologies
Development of Chatbot Using AI\ML Technologies
MaisnamLuwangPibarel
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
ssuser2b426d1
 
React Native vs Flutter - SSTech System
React Native vs Flutter  - SSTech SystemReact Native vs Flutter  - SSTech System
React Native vs Flutter - SSTech System
SSTech System
 
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
Semiosis Software Private Limited
 
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
Roshan Dwivedi
 
Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
Philip Schwarz
 
Cultural Shifts: Embracing DevOps for Organizational Transformation
Cultural Shifts: Embracing DevOps for Organizational TransformationCultural Shifts: Embracing DevOps for Organizational Transformation
Cultural Shifts: Embracing DevOps for Organizational Transformation
Mindfire Solution
 
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdfResponsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Trackobit
 
dachnug51 - Whats new in domino 14 .pdf
dachnug51 - Whats new in domino 14  .pdfdachnug51 - Whats new in domino 14  .pdf
dachnug51 - Whats new in domino 14 .pdf
DNUG e.V.
 
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdfWhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
onemonitarsoftware
 
Migrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS CloudMigrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS Cloud
Ortus Solutions, Corp
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Asher Sterkin
 

Recently uploaded (20)

Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
 
Safe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work PermitsSafe Work Permit Management Software for Hot Work Permits
Safe Work Permit Management Software for Hot Work Permits
 
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdfAWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) AWS Security .pdf
 
Splunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptxSplunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptx
 
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
 
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
 
Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)Software development... for all? (keynote at ICSOFT'2024)
Software development... for all? (keynote at ICSOFT'2024)
 
Development of Chatbot Using AI\ML Technologies
Development of Chatbot Using AI\ML TechnologiesDevelopment of Chatbot Using AI\ML Technologies
Development of Chatbot Using AI\ML Technologies
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
 
React Native vs Flutter - SSTech System
React Native vs Flutter  - SSTech SystemReact Native vs Flutter  - SSTech System
React Native vs Flutter - SSTech System
 
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
 
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
FAST Channels: Explosive Growth Forecast 2024-2027 (Buckle Up!)
 
Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
 
Cultural Shifts: Embracing DevOps for Organizational Transformation
Cultural Shifts: Embracing DevOps for Organizational TransformationCultural Shifts: Embracing DevOps for Organizational Transformation
Cultural Shifts: Embracing DevOps for Organizational Transformation
 
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdfResponsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
 
dachnug51 - Whats new in domino 14 .pdf
dachnug51 - Whats new in domino 14  .pdfdachnug51 - Whats new in domino 14  .pdf
dachnug51 - Whats new in domino 14 .pdf
 
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdfWhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
 
Migrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS CloudMigrate your Infrastructure to the AWS Cloud
Migrate your Infrastructure to the AWS Cloud
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
 

Creating a full stack web app with python, npm, webpack and react

  • 1. CREATING A FULL STACK WEB APP WITH PYTHON, NPM, WEBPACK AND REACT by Angela Branaes
  • 6. THE STRUCTURE OF A WEB APP ➤ Separated into front and back end. ➤ Multiple technologies. ➤ Front end is: ➤ Look and feel. ➤ User interaction. ➤ Back end is: ➤ Long running operations. ➤ Data, and data processing. ➤ Application logic.
  • 7. INITIAL PROJECT SETUP ➤ Create the following directory structure . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ └── js/ $ cd fullstack_template/static
  • 8. WE’RE GOING TO NEED A JAVASCRIPT PACKAGE MANAGER ➤ Using a package manager makes it painless to: ➤ Keep your project dependencies up to date. ➤ Fetch and install new packages. ➤ Similar to brew, pip, pacman etc.
  • 9. NPM
  • 10. NPM = NODE PACKAGE MANAGER ➤ Automatically included with Node.js ➤ Easy to use ➤ well documented ➤ nearly 500 000 packages available ➤ Initialise NPM: $ npm init ➤ This creates a file called package.json
  • 11. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ └── package.json
  • 12. THE PURPOSE OF PACKAGE.JSON 1. Keeps track of dependencies and versions. 2. Informs other developers about your project. 3. Makes installing, running and updating a project automatic and reproducible
  • 13. THIS IS MY PACKAGE.JSON { "name": "FullStackTemplate", "version": "1.0.0", "description": "Fullstack Template", "main": "index.jsx", "scripts": { "test": "echo "Error: no test specified" && exit 1", }, "keywords": [ "python", "react", "npm", "webpack" ], "author": "Angela Branaes", "license": "MIT", "devDependencies": { "webpack": "^3.0.0" } }
  • 14. WHY WE NEED A MODULE BUNDLER ➤ Minimises the number of <script> tags in your HTML ➤ This means faster loading, and less hassle. ➤ Don’t need to worry about bundle import ordering! ➤ Don’t have to use globals or namespacing. ➤ Lazy module loading. ➤ We will be using Webpack.
  • 16. WEBPACK ➤ Only understands JavaScript. ➤ Everything else needs a loader or plugin. ➤ Everything is a module. ➤ You can require() JavaScript, React, CSS or images. ➤ Creates a dependency tree of all your required modules, and packages those into bundles. ➤ Easy to get started with, if you only need JavaScript. ➤ Minor learning curve for css/less and image loading. ➤ Lets you split your bundles and load them asynchronously and lazily. ➤ Integrates seamlessly with npm.
  • 17. INSTALL & CONFIGURE WEBPACK ➤ Install webpack: $ npm i webpack --save-dev ➤ Add a file named webpack.config.js: const webpack = require(‘webpack'); const config = { entry: __dirname + '/js/index.jsx', output: { path: __dirname + '/dist', filename: 'bundle.js', }, resolve: { extensions: ['.js', '.jsx', '.css'] }, }; module.exports = config;
  • 18. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ ├── package.json └── webpack.config.js
  • 19. SINGLE VS MULTI PAGE APPLICATIONS ➤ I mostly use Webpack for single page applications. ➤ You can also use webpack for multi page applications: entry: {
 “indexPage”: __dirname + “js/index.jsx”,
 “aboutPage”: __dirname + “js/about.jsx” }, output: { path: __dirname + “/dist”,
 filename: “[name].js” //e.g. aboutPage.js }
  • 21. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ │ └── bundle.js ├── images/ ├── js/ │ └── index.jsx ├── index.html ├── package.json └── webpack.config.js
  • 22. CREATE INDEX.HTML ➤ A really simple index.html is all you need. ➤ The index.html just loads your JavaScript bundle <body> <div id="content" /> <script src="dist/bundle.js" type=“text/javascript”> </script> </body> ➤ All the layout and behaviour live in the JS/React files!
  • 23. CREATE INDEX.JSX ➤ Just 1 line of Plain Old JavaScript alert(“Hello World!”);
  • 24. BUILDING YOUR APPLICATION ➤ Create run commands to simplify building your code. ➤ Run commands are just aliases. ➤ Example from my package.json: “scripts": { "watch": "webpack --progress -d --config webpack.config.js —watch" } ➤ Makes the dev process more fluid. ➤ I always add the following: ➤ build ➤ dev-build ➤ watch
  • 25. START THE WATCH COMMAND ➤ Any changes get built automatically $ npm run watch ➤ Open index.html….
  • 27. CREATING A SIMPLE REACT APP
  • 28. THE BENEFITS OF USING REACT ➤ Easy to build UIs composed of small, distinct components. ➤ Encourages design of reusable UI components. ➤ Easier to understand what’s going on when markup lives with the code (JSX). ➤ Automatic re-rendering of components on change. ➤ Easy to maintain.
  • 29. INSTALL REACT $ npm i react react-dom —save-dev
  • 30. REACTIFY INDEX.JSX import React from "react"; import ReactDOM from "react-dom"; import App from “./App"; ReactDOM.render(<App />, document.getElementById("content"));
  • 31. ADD A REACT “APP” CLASS ➤ Remember to export your react classes! // App.jsx import React from “react”; export default class App extends React.Component { render () { return <p> Hello React!</p>; } }
  • 32. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ │ ├── index.jsx │ └── App.jsx ├── index.html ├── package.json └── webpack.config.js
  • 33. WHAT IS JSX? ➤ Syntax extension to JavaScript. ➤ Optimised on compilation, so faster than JavaScript. ➤ Statically typed and mostly type-safe. JavaScript is not. ➤ Lets you write HTML tags in your JavaScript functions: <Hello name=“Rimini” /> instead of React.createElement(Hello, {name: “Rimini}, null) ➤ Recognises upper-case element-types as written in React. E.g. <Hello /> ➤ How do we make our browser understand JSX?
  • 34. INTRODUCING BABEL Write next-generation javascript right now! Transform JSX to JS.
  • 35. ADD BABEL ➤ Install Babel ➤ Add the Babel presets to the package.json: “babel”: { “presets”: [ “es2015”, “react” ] },
  • 36. ADD A BABEL-LOADER RULE TO THE WEBPACK CONFIG: module: { rules: [ { test: /.jsx?/, exclude: /node_modules/, use: 'babel-loader' } ] }
  • 37. OPEN INDEX.HTML IN YOUR BROWSER ➤ This should now show the “Hello React” paragraph we added in our new React App.jsx file.
  • 40. PYTHON ➤ Go to the server folder ➤ Ensure you’re in a Python virtualenv $ mkvirtualenv fullstack ➤ Install Flask (fullstack)$ pip install flask ➤ Create a file called server.py in the server folder
  • 41. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ │ ├── index.jsx │ └── App.jsx ├── index.html ├── package.json └── webpack.config.js
  • 42. SERVER.PY from flask import Flask, render_template app = Flask(__name__, static_folder=“../static/dist", template_folder="../static") @app.route("/") def index(): return render_template("index.html") @app.route("/hello") def hello(): return "Hello World!” if __name__ == "__main__": app.run()
  • 43. START THE SERVER ➤ Go to: http://localhost:5000/ $ python server.py
  • 44. REQUEST INFO FROM THE SERVER var $ = require(‘jquery'); getPythonHello() { $.get(window.location.href + 'hello', (data) => { console.log(data); this.personaliseGreeting(data); }); }
  • 45. MAKE PYTHON DO SOMETHING MORE INTERESTING ➤ We call get_hello() whenever we hit the /hello endpoint def get_hello(): greeting_list = ['Ciao', 'Hei', 'Salut', 'Hola', 'Hallo', 'Hej'] return random.choice(greeting_list)
  • 46. SAY HI TO SOMEONE SPECIAL ➤ There should be a class for that! ➤ Change the App.jsx render method to the following: render () { return ( <PageHeader> <div className='header-contents'> <Hello name='Rimini' /> </div> </PageHeader> ); )
  • 47. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ │ ├── index.jsx │ ├── App.jsx │ └── Hello.jsx ├── index.html ├── package.json └── webpack.config.js
  • 48. CREATE THE HELLO CLASS export default class Hello extends React.Component { constructor(props) { super(props); // greeting is now “Hello Rimini” this.state = {greeting: 'Hello ' + this.props.name}; // This binding is necessary to make `this` // work in the button callback this.getPythonHello = this.getPythonHello.bind(this); } }
  • 49. ➤ Add this function to the Hello class: ➤ This will re-render the greeting on our website to a new one when called. personaliseGreeting(greeting) { this.setState({greeting: greeting + ' ' + this.props.name + '!'}); }
  • 50. LET’S FINALLY RENDER OUR HELLO! render () { return ( <h1>{this.state.greeting}</h1> <hr/> <Button onClick={this.getPythonHello}> Say Hello! </Button> ); }
  • 53. CREATE A NICE LAYOUT WITH CSS ➤ Webpack ONLY understands JavaScript. ➤ Install the following loaders and plugins: ➤ style-loader ➤ css-loader ➤ extract-text-webpack-plugin ➤ Add a plugin to the webpack config: plugins: [ new ExtractTextPlugin('styles.css'), ]
  • 54. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ │ └── fullstack.css ├── dist/ │ ├── bundle.js │ └── styles.css ├── images/ ├── js/ │ ├── index.jsx │ ├── App.jsx │ └── Hello.jsx ├── index.html ├── package.json └── webpack.config.js
  • 55. ➤ Add fullstack.css to the css folder ➤ Add a few css rules for our header ➤ require fullstack.css in App.jsx: require(‘../css/fullstack.css'); ➤ Add the bundled css to the index.html: <link rel="stylesheet" href="dist/styles.css">
  • 57. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ │ └── fullstack.css ├── dist/ │ ├── bundle.js │ └── styles.css ├── images/ │ └── header.png ├── js/ │ ├── index.jsx │ ├── App.jsx │ └── Hello.jsx ├── index.html ├── package.json └── webpack.config.js
  • 58. ADD A NICE BACKGROUND IMAGE 1. Add the file-loader loader 2. Add an image to your images/ folder 3. Set the image to be your header background in the fullstack.css file background-image: url(‘../images/header.jpg’); 4. NOTE: you have to load the image in your React app for it to show up!
  • 59. IN APP.JSX import HeaderBackgroundImage from ‘../images/header.jpg’; ➤ Add this fn to your class: addHeaderImg() { let headerBg = new Image(); headerBg.src = HeaderBackgroundImage; } ➤ And this to your render(): {this.addHeaderImg()}
  • 64. THANK YOU! ANY QUESTIONS? @angineering @angineering - The code is on GitHub: https://github.com/angineering/FullStackTemplate @angineering - This talk is also a blogpost