Flask webpack

Flask webpack DEFAULT

A Template for Creating a Full Stack Web Application with Flask, NPM, Webpack, and Reactjs

Why are some people more successful than others? Why do some people make more money, live happier lives, and accomplish much more in the same number of years than the great majority? What is the real “secret of success?”

Unless you become more of a doer than a thinker, you would find it hard to accomplish anything meaningful. The ability to create a full-stack web application will give you the freedom to quickly bring your great idea to existence and to the reach of everybody as we all know our world is internet driven.

The aim of this article is to help you start your own full-stack web application with a Python Flask server and a React front-end. This article is suitable for anyone with a basic understanding of programming and technology who wants to explore the beauty of python-flask, npm, webpack and reactjs to build a full-stack web app.

This blog will go through the implementation which can be found in this GitHub link here. However, you will gain more if you follow along this blog post.

Folders and Files Organisation

We will start by organizing files and folders for our project. Organizing static files such as JavaScript, stylesheets, images, and so on efficiently is always a matter of concern for all web framework. Flask recommends a specific way to organize static files in our application

├── hello_template
├── configurations.py
├── __init__.py
├── README.md
├── run.py
└── templates
├── hello
│ ├── __init__.py
│ └── views.py
├── __init__.py
├── public
│ ├── css
│ ├── fonts
│ ├── images
│ └── js
└── static
├── index.html
├── __init__.py
├── js
├── components
├── index.jsx
└── routes.js

We have arranged our application in a modular manner. We achieved this by using the file in our folders, which are to be used as modules.

Flask Configuration

Flask is a microframework for Python based on Werkzeug, Jinja2, and good intentions

Why micro? It simply refers to the fact that Flask aims at keeping the core of the framework small but highly extensible. This makes writing applications or extensions very easy and flexible and gives developers the power to choose the configurations they want for their application, without imposing any restrictions on the choice of database, templating engine, and so on.

I assume here that you have already set up your Python environment. If not, following this link to install python and get things ready. Lets continue by installing Flask by running the following command

To be sure everything is working fine, let’s create a fast and simple Flask-based web application. Copy the code below and paste it in the file and save.

from flask import Flask
app = Flask(__name__)
def hello_world():
return 'Hello to the World of Flask!'
if __name__ == '__main__':

In this code as well as in any other code of this article, make sure you indent the code where appropriate

Open a terminal in root directory and execute the following command to run the application:

If all is working correctly, you will be given an address which you can open in your favorite browser and see our application running.

To see all packages which Flask depends on, you may install Flask with the command The refers to the installation with upgrades. Also, this will list all the packages on which Flask depends, which happens to be , and . Flask won’t work if any of them are missing

Class-based Settings: We should bare in mind that this is just a template, however, as the project gets bigger, you can have different deployment modes such as production, testing, staging, and so on, where each mode can have several different configuration settings and some settings will remain the same.
For this project, we will use a class-based setting, where we will have a default setting base class, and other classes can inherit this base class and override or add deployment-specific configuration variables.

Open the file and paste the below code.

class BaseConfig(object):
Base config class
DEBUG = True
TESTING = Falseclass ProductionConfig(BaseConfig):
Production specific config
DEBUG = Falseclass DevelopmentConfig(BaseConfig):
Development environment specific configuration
DEBUG = True

Now, we can use any of the preceding classes while loading the application’s configuration via in as:

from templates import app
#Load this config object for development mode


Enabling the debug mode will make the server reload itself in the case
of any code changes, and it also provides the very helpful Werkzeug
debugger when something goes wrong.

Also, notice here that we imported from templates. We are going to define our in the file in the folder. The importation here is possible because we have arranged our application in a modular manner

Loading Static files: If there exists a folder named at the application’s root level, that is, at the same level as , then Flask will automatically read the contents of the folder without any extra configuration. Alternatively, we can provide a parameter named to the application object while defining the application in file

from flask import Flaskapp = Flask(__name__,
static_folder = './public',
template_folder="./static")import templates.hello.views

Then, we will have an empty file just to make the enclosing folder a Python package. Finally, the will be:

from templates import app
from flask import [email protected]('/')
def index():
return render_template("index.html")

We can identify a circular import between and , where, in the former, we import views from the later, and in the latter, we import the app from the former. So, this actually makes the two modules depend on each other.

In our hello folder, we used the views to render an HTML file which will be displayed whenever it sees at the end of the url and . So the normal execution process will be:

  • Start the application from
  • imports app from
  • initializes the app and imports all the views
  • listen to the url and and renders an html file.

we used to render an HTML file instead of generating the HTML from the Python which is no fun, and actually pretty cumbersome because you have to do HTML escaping on your own to keep the application secure. And we will notice that we had configured our app with hence the static folder will contain our HTML template files which could be loaded directly without specifying the path again. You can read more from here

is React specific. We will cover how to install React later

Making our web app modular with blueprints: A blueprint is a concept in Flask that helps make larger applications really modular. It is actually a set of operations that can be registered on an application and represents how to construct or build an application. We will modify our views to work using blueprints.

First, our will be modified as

from flask import Flaskapp = Flask(__name__,
static_folder = './public',
template_folder="./static")from templates.hello.views import hello_blueprint# register the blueprints

Next, the will be modified as

from flask import render_template, Blueprinthello_blueprint = Blueprint('hello',__name__)@hello_blueprint.route('/')
def index():
return render_template("index.html")

We have defined a blueprint in the view file, we don’t need the app object anymore here, and our complete routing is defined on a blueprint named . So instead of , we used . The same blueprint is imported in and registered on the application object. A rule of thumb is that each view should have its own blueprint.

Installing and Configuring Webpack

webpack is a module bundler which will be used for JSX transformation and module/dependency bundling. The usage of modules helps organize JavaScript code by splitting it into multiple files, each one declaring its own dependencies. The module bundler then automatically packs everything together in the correct load order.

A lot of tools that handle this intermediary step, including Grunt, Gulp, and Brunch, among others. But in general, the React community has adopted webpack as the preferred tool for this job.

Installing Webpack: Webpack can be installed through . Install it globally using or add it as dependency in your project with

In this project, we will add webpack as dependency. So we first create a file. To create this file, you can open a terminal in the folder and run the command

The file is a standard npm manifest that holds various information about the project and let the developer specify dependencies( that can get automatically downloaded and installed) and define script tasks.

The command will ask you a series of questions regarding your project( such as project name, description, information about the author, etc.).

With a package.json file in place, install webpack and the webpack cli with

Note: Every installations we will do with should be at a terminal opened in the directory where resides.

Defining a Config File: The basic command line syntax for webpack is “”. Webpack requires you to point only one entry file — it will figure out all the project’s dependencies automatically. Additionally, if you don’t have webpack installed globally like in our case, you will need to reference the webpack command in the folder of the project. The command will look like this:

However, webpack has a lot of different and advance options and allows for the usage of loaders and plugins to apply transformation on the loaded modules. Although its possible to use webpack with all options from the command line as above, the process tends to get slow and error-prone. A better approach is to define a configuration file — a simple JavaScript module where you can put all information relating to your build.

Create a file . It must reference the entry file and the destination for the bundled file as shown below:

const webpack = require('webpack');
const resolve = require('path').resolve;const config = {
entry: __dirname + '/js/index.jsx',
path: resolve('../public'),
filename: 'bundle.js',
publicPath: resolve('../public')},
resolve: {
extensions: ['.js','.jsx','.css']
};module.exports = config;

is a node.js global variable containing the name of the directory that the currently executing script resides in.

The file created by webpack will be stored in the public folder as indicated in above.

Add Run Command: To make the development process more fluid, we will add some few run commands (build, dev-build, and watch) to the package.json file.

Build is used for production builds, and dev-build for non-minified builds. Watch is similar to dev-build, with the added benefit that it monitors your project files. Any changed files will be automatically rebuilt, and refreshing your browser will show the changes you just made.

Here is the package.json

"name": "hello_template",
"version": "1.0.0",
"description": "A template for creating a full stack wep app with Flask, NPM, Webpack, and Reactjs",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p --progress --config webpack.config.js",
"dev-build": "webpack --progress -d --config webpack.config.js",
"watch": "webpack --progress -d --config webpack.config.js --watch"

"repository": {
"type": "git",
"url": "git+https://github.com/Eyongkevin/my-portfolio.git"
"keywords": [
"author": "Eyong Kevin",
"license": "ISC",
"bugs": {
"url": "https://github.com/Eyongkevin/my-portfolio/issues"
"homepage": "https://github.com/Eyongkevin/my-portfolio#readme",
"devDependencies": {
"webpack": "^4.19.1",
"webpack-cli": "^3.1.0"

Your may be different from mine due to the answers you may have provided during the creating of this file with

You may notice some variables with my personal information like , and . You may want to change it to your own personal information.

Generating source maps: One of the most important and used configurations for webpack is Source Maps. While packing together all of your project’s JavaScript modules into one( or a few) bundled file to use on the browser present a lot of advantages, one clear disadvantage is that you won’t be able to reference back your original code in their original files when debugging in the browser. It becomes very challenging to locate exactly where the code you are trying to debug maps to your original authored code. This is where Source Maps comes in — A source map provides a way of mapping code within a bundled file back to its original source file, making the code readable and easier to debug in the browser.

To configure Webpack to generate source maps that points to the original files, we use the setting. It has many options but for this project, we will be using the ‘’ as it generates a complete source map. Though it comes with some disadvantages, we will use it only on development mode.

const webpack = require('webpack');
const resolve = require('path').resolve;const config = {
devtool: 'eval-source-map',
entry: __dirname + '/js/index.jsx',
path: resolve('../public'),
filename: 'bundle.js',
publicPath: resolve('../public')},
resolve: {
extensions: ['.js','.jsx','.css']
};module.exports = config;

There are even faster options for devtool. Although faster, these
options don’t map the bundled code straight to the original source
files, and are more appropriate for bigger projects were build times
are a concern. You can learn more about all the available options at
webpack’s documentation

Loaders: One of the most exciting features of Webpack are loaders. Through the use of loaders, webpack can preprocess the source files through external scripts and tools as it loads them to apply all kinds of changes and transformations. The transformations are useful in many circumstances, for example for parsing JSON files into plain JavaScript or turning next generation’s JavaScript code into regular JavaScript that current browsers can understand. Loaders can be configured under the “” key in .

Loader configuration setting includes:

  • test: A regular expression that matches the file extensions that should run through this loader (Required).
  • loader: The name of the loader (Required).
  • include/exclude: Optional setting to manually set which folder and files the loader should explicitly add or ignore.
  • query: The query setting can be used to pass additional options to the loader.

In this project, we will use babel as our loader to transform React’s JSX into plain JavaScript as below:

const webpack = require('webpack');const config = {
devtool: 'eval-source-map',
entry: __dirname + '/js/index.jsx',
path: __dirname + '/dist',
filename: 'bundle.js',},
resolve: {
extensions: ['.js','.jsx','.css']
module: {
rules: [
test: /\.jsx?/,
loader: 'babel-loader',
exclude: /node_modules/,

};module.exports = config;

The loader that is used in the above code is ‘’. Continue below to see how to install and configure babel.

We had excluded here because we won’t want babel to transform any node modules hence making the loading faster.

Add Babel Support

Babel is a platform for JavaScript compilation and tooling. It let you;

  • Use next versions of JavaScript (ES6, ES2015, ES2016, etc), not yet fully supported in all browsers
  • Use JavaScript syntax extensions, such as React’s JSX

Though babel is a stand alone tool, we will use it in this project as a loader since it pairs very well with Webpack.

Babel is distributed in different npm modules. The core functionality is available in the “” npm package, the integration with webpack is available through the “” npm package, and for every type of feature and extensions we want to make available to our code, we will need to install a separate package (the most common are and , for compiling ES6 and React’s JSX respectively).

Open a terminal in the directory and install babel and all the feature needed for this project as development dependencies with the command:

Now that we have installed babel, we can enable our project to use ES6 modules and syntax, as well as JSX by adding as presets in the file.

const webpack = require('webpack');const config = {
devtool: 'eval-source-map',
entry: __dirname + '/js/index.jsx',
path: __dirname + '/dist',
filename: 'bundle.js',},
resolve: {
extensions: ['.js','.jsx','.css']
module: {
rules: [
test: /\.jsx?/,
loader: 'babel-loader',
exclude: /node_modules/,
presets: ['react','es2015']
};module.exports = config;

However, many developers opt to create a separate babel resource configuration-namely, a file( with a leading dot). The only babel-specific configuration we have in place so far is the presents definition-which may not justify the creation of a babel-specific configuration file. But since additional webpack and babel features will be added with time, we are better off using babel configuration file.

Create a file in the directory:
In Linux, you can use
This will create an unsaved file which you can fill in the codes below and save

“presets”: [“react”, “es2015”]}

Babel will look for a in the current directory of the file being transpiled. If one does not exist, it will travel up the directory tree until it finds either a or a with a hash within. You can read more from the official website

Add Reactjs

React is an open-source project created by Facebook. It offers a novel approach towards building user interfaces in JavaScript.

There are a lot of JavaScript MVC frameworks out there. So why did Facebook build React and why would we use it in this project?

  • Reactive Rendering is Simple: Most JavaScript frameworks use data binding to keep the interface in sync with the state, which comes with disadvantages in maintainability, scalability, and performance. React lets you write in a declarative way how components should look and behave. And when the data changes, React conceptually renders the whole interface again. Conceptually in the sense that it uses an in-memory, lightweight representation of the DOM called “”.
  • Component-Oriented Development Using Pure JavaScript: In React application, everything is made of components, which is self-contained, concern-specific building blocks. It allows a “divide and conquer” approach where no particular part needs to be especially complex. So it’s easy to create complex and more feature-rich components made of smaller components. These components are written in plain JavaScript, instead of template languages, this gives you a full-featured programming language to render views because template languages can be limiting

Install Node.js: To follow along, you will need to have Node.js installed. JavaScript was born to run on the browser, but Node.js makes it possible to run JavaScript programs on your local computer and on a server. If you don’t have Node.js installed, you can install it now by downloading the installer for Windows, Mac or Linux here.

Install React: Open a terminal in and run the command

$ npm i react react-dom --save-dev

Creating .js and .jsx files: We recall that our file imported our views from folder. And the file in the hello folder Will listen to a url and render a template file ’ which is found in the directory . This HTML file is almost empty, it simply loads the bundled javaScript and provides a Div in which to render react components.

<!— index.html —>
<meta charset="utf-8">
<!-- Latest compiled and minified bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<title>Creating a Full-Stack Python Application with Flask, NPM, React.js and Webpack</title>
<div id="content" />
<script src="public/bundle.js" type="text/javascript"></script>

This HTML file’s location was specified in with the variable

The file here is the webpack’s single JavaScript file containing all the modules packed in the correct order. And it’s location is been specified in as

Now we will fill the file with a simple React app, and have it load the appropriate component from a router file into our file

import React from 'react';
import ReactDOM from 'react-dom';
import routes from "./routes";ReactDOM.render(routes, document.getElementById("content"));

Our file will do the work of calling the appropriate components and consequently displaying our “Hello React!” message.

Installing react router: React Router is the most popular solution for adding routing to a React application. It keeps the UI in sync with the URL by having components associated with routes (at any nesting level). When the user changes the URL, components get unmounted and mounted automatically.

Router is an external library, it must be installed with npm (along with the History library, which is a React Router peer dependency

Using npm:

Add the following code into the file:

import React from 'react';
import { HashRouter, Route, hashHistory } from 'react-router-dom';
import Home from './components/Home';
// import more components
export default (
<HashRouter history={hashHistory}>
<Route path='/' component={Home} />

imports the class from , so this class needs to be exported for it to be importable.

Remember we said the file contains a Div in which to render react component. We see that has a Div with Id ‘’ in which renders the routes from

React Components:In a React application, everything is made of components, which are self-contained, concern-specific building blocks. Developing applications using components allows a “divide and conquer” approach where no particular part needs to be especially complex. They are kept small and because they can be combined, it’s easy to create complex and more feature-rich components made of smaller components.

Using React components architecture comes with some advantages like:

  • It enables the use of the same principles to render HTML for the Web as well as native iOS and Android view
  • Events behave in a consistent, standards-compliant way in all browsers and devices, automatically using delegation.
  • React components can be rendered on the server for SEO and perceived performance

So React components are just building blocks of React UIs which simply consist of a JavaScript class with a render method that returns a description of the component’s UI.

In this project, we will create just one component which will describe our web app home page. However, we should create for each UI, a component which will take care of describing the specified UI.

Enter the code below into the file

import React, { Component } from 'react';
export default class Home extends Component {
render() {
return (
<h1>Hello React!</h1>

We can notice the HTML tags in the middle of the JavaScript code. As mentioned, React has a syntax extension to JavaScript called JSX that lets us write XML(and consequently HTML) inline with code. Hence we had used babel to transform the JSX into plain JavaScript.

Stylesheets: Webpack provides two loaders to deal with stylesheets: and . Each loader deals with different tasks: While the css-loader looks for and statements and resolves them, the style-loader adds all the computed style rules into the page. Combined together, these loaders enable you to embed stylesheets into a Webpack JavaScript bundle.

Install css-loader and style-loader with npm

In sequence, update the webpack configuration file, as shown below:

const webpack = require('webpack');
const config = {
devtool: 'eval-source-map',
entry: __dirname + '/js/index.jsx',
path: __dirname + '/dist',
filename: 'bundle.js',
resolve: {
extensions: ['.js','.jsx','.css']
module: {
rules: [
test: /\.jsx?/,
loader: 'babel-loader',
exclude: /node_modules/,
test: /\.css$/,
loader: 'style-loader!css-loader?modules'
module.exports = config;

The exclamation point (“!”) can be used in a loader configuration to chain different loaders to the same file types

From webpack v4, the automatic -loader module name extension has been removed. It is no longer possible to omit the extension when referencing loaders. So instead of the former now it is

Now lets write a simple css file just to illustrate. Copy the code below in to the file

html {
box-sizing: border-box;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
*, *:before, *:after {
box-sizing: inherit;
body {
margin: 0;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
h1, h2, h3, h4, h5, h6, p, ul {
margin: 0;
padding: 0;

Finally, we should remember that Webpack starts on an entry file defined in its configuration file and build all the dependency tree by following statements like import, require, url among others. This means that the main CSS file must also be imported somewhere in the application in order for webpack to find it.

Let’s import our into

<!- index.html ->
<meta charset="utf-8">
<!-- Latest compiled and minified bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<link rel="stylesheet" href="public/css/main.css">
<title>Creating a Full-Stack Python Application with Flask, NPM, React.js and Webpack</title>
<div id="content" />
<script src="public/bundle.js" type="text/javascript"></script>

Running the App

Open a terminal in the folder and start a development watch server

npm run watch

If you get an error here similar to **npm WARN [email protected] requires a peer of @babel/core@⁷.0.0 but none was installed.**, then you should downgrade your babel-loader to 7.x as follows:

Open a terminal at the root directory of this project and start the python server

python run.py

If all is working correctly, you will be given an address which you can open in your favorite browser and see our application running and displaying “Hello React!

And that’s it. You’ve just created your basic full-stack application.

Thank you for your time, I would be updating this article accordingly. You can contribute by commenting, suggesting and sharing this article so that we can together, educate the world.

Also, if you like this article, you may want to continue learning by following the continuation of this article here, where we will see how to make our web application component-oriented and data-driven

I will be releasing more articles like this, so make sure you follow me here on Medium so that you won’t miss any of my new releases.

Sours: https://itnext.io/a-template-for-creating-a-full-stack-web-application-with-flask-npm-webpack-and-reactjs-be2294b111bd

Hey! This repo is no longer supported!

Flask-Webpack has been deprecated in favor of: https://github.com/nickjj/flask-static-digest

The new Flask-Static-Digest extension is easier to use, easier to configure, works with any (or no) asset build tool and is completely stand alone.

Instead of depending on Webpack to handle md5 tagging assets and creating a manifest, Flask-Static-Digest does all of that and now it even gzips your files too.

This makes it a general purpose extension that you can use to make your static files production ready.

This will be the final commit to this project. Farewell Flask-Webpack, you were a good friend!

PyPI versionBuild status

What is Flask-Webpack?

Managing assets can be a serious burden. Here's just a few things you get by using this package:

  • Minify assets
  • Attach vendor prefixes to your CSS automatically
  • Optimize image sizes
  • Leverage the CommonJS module system to organize your Javascript
  • Compile Markdown
  • Compile 20+ client side template languages
  • Compile LESS, SASS and any other CSS pre-processor you can imagine
  • Compile Typescript, Coffeescript and any other to-javascript language
  • Compile Ecmascript 6 (ES) down to ES 5
  • Compile React JSX to JS with hot module reloading
  • Near instant compile times, ~20-50ms is common on my workstation
  • Optionally get source maps in development mode
  • Serve your assets from a tricked out local development asset server
  • Cache all assets forever because their file names get md5-tagged
  • The only runtime you need other than Python is NodeJS
  • Never deal with file watchers again because it's all taken care of for you
  • And much more...

All of the features above are the direct result of using Webpack to manage your assets. The huge win here besides the obvious is that the functionality is outside of this package.

That means you have free reign to pick and choose what you want without having to worry about Flask-Webpack versions. If a new Webpack plugin becomes available, you can use it immediately.

What does this package do then?

It sets up a few template tags so you can access the assets inside of your jinja templates.

It means you can type this:

...and once your jinja template has been compiled, you will see this:

Now you can happily tell your frontend proxy to cache that hamburger image for an entire year. If you ever change the hamburger, the md5 will change but you do not need to change any of your templates because the tag knows how to look it up.

Global template tags

  • asset_url_for(asset_relative_path) to resolve an asset name
  • javascript_tag(*asset_relative_paths) to write out 1 or more script tags
  • stylesheet_tag(*asset_relative_paths) to write out 1 or more stylesheet tags

Both the javascript and stylesheet tags accept multiple arguments. If you give it more than argument it will create as many tags as needed.


Quick start

from flask import Flask from flask_webpack import Webpack webpack = Webpack() app = Flask(__name__) webpack.init_app(app)

You can view a complete working example in the test app.

There's also a blog post and short video explaining how to use this extension.

How does it work?

It expects you to have built a manifest file and it handles the rest. You can build this manifest file using a plugin I wrote for Webpack. You can find that plugin here.

This process is done automatically upon starting the dev asset server or building your assets to prepare for a production release. All of that is taken care of in the file.


is configured like most Flask extensions. Here's the available options:

  • : default
    • Required: You may consider using , it's up to you.
  • : default
    • Optional: Use this asset url instead of the .
    • You would set this to your full domain name or CDN in production.

Learn more

Webpack knowledge

Most of what you'll need to learn is related to Webpack specifically but the example app in this repo is enough to get you started. Here's a few resources to help you get started with Webpack:

Help! My assets do not work outside of development

I see, so basically the problem is you're using the function in your stylesheets and are referencing a relative path to an asset, such as:

The above works in development mode because that's where the file is located but in production mode the asset is not there. The template helper handles all of this for you on the server side but now you need some assistance on the client side as well.

You have a few options here depending on if you're using CSS, SASS or something else. If you're using straight CSS you will need to pre-prend all of your paths with a special identifier.

If you were to re-write the example from above, it would now be:

That will automatically get expanded to a path that works in every environment.

If you're using SASS you can create your own function to make things easier to work with on a day to day basis. Something like this should suffice:

@function asset-url($path) { @return url('~!file!' + $path); }

Now you can call it like this and everything will work:

Feel free to make additional helper functions that let you abstract away the relative prefix such as or . It really depends on how your assets are set up.


Sours: https://github.com/nickjj/flask-webpack
  1. Dailyhaha games
  2. Frog speaking chinese meme
  3. 2013 buick regal

React-Flask Integration: Part 1 - Setup with Webpack

Hi !
This is a two part article. In the first part, we will connect react with flask and use webpack for transpiling JSX to browser readable JavaScript. In the second part, I'll talk about passing data from flask to react and vice-versa.

GitHub Repo: https://github.com/IceWreck/Flask-React-Boilerplate

Exploring Different Solutions

  • Develop + host flask and react separately. Connect them via an API. This is what most projects do. This approach is perfectly fine but not suitable if you want to use react in a part of your website instead of letting it control the flow.
  • Use create-react-app (CRA) and serve react from flask. This method is somewhat hacky as you have to make flask work with CRA's directory structure. You cannot have two completely independent react components in your application.
  • Eject your react app from CRA and then serve react from flask. Ejecting gives you the webpack configuration underneath CRA. However, this may leave some bloat and additional scripts that you probably do not need. You have to edit the leftover webpack configuration anyways, so why not just make your own ? This brings us to the next solution.
  • Creating your own toolchain. This gives you the freedom to use as much (or as little) react as you like. I'll go with this approach in this tutorial.

Let's Begin

Like react's docs recommend, we need a JavaScript package manager like yarn or npm and a bundler like webpack.

This tutorial will use yarn, a safer, faster and slightly less messier alternative to npm. Yarn is just a frontend, it uses the npm registry under the hood.

You can use npm if you like, the yarn commands mentioned here will have to be slightly changed but in the end it comes down to personal preference.

So what is webpack ?

Webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.

In fact, create-react-app is an abstraction on top of webpack.

This article explains webpack in detail.

Webpack Infographic

Out of the box, webpack only understands JavaScript and JSON files. Loaders allow webpack to process other types of files and convert them into valid modules that can be consumed by your application and added to the dependency graph.

In your empty project directory

Note that means that its a development dependency.

Fill up some meta information like name, etc and your package.json should look something like this:

In the same directory, create a virtual environment if you want to and install flask.

Now, we will setup flask. Create a file called and two empty directories called and . Create your flask application.


I've set flask to run in debug mode by default but you can remove this if you want and configure debug mode via an environment variable.


This is regular jinja templating. Do whatever you do in flask. To add a react component, create an empty and add an id like render-react-here.

Our very basic flask setup is essentially done . Now comes the react part.


This file is the entrypoint of your independent react componenent which is placed in your flask/jinja template ().
After configuration, webpack will take care of any other components, css files and images that are imported here or in any child components.

If you want to create another independent react component to add to flask, go ahead and create .

Now lets do our webpack configuration.

In our main project directory, create and



Woah! Thats quite a mouthful.

  • The object at the top is called and the one at the bottom is called . We specify the entrypoint files of our independent components we want webpack to process and the output format of the compiled and minified JavaScript file.
  • Here, we name our file as . So output file will be which is fed into the flask/jinja template. If you created add it to the webpack config as well and name it something else.
  • The module section has loaders. Babel will convert JSX (the html like tags we use in react) into pure JavaScript. The file-loader will take care of any files (images) we load into our react components. The style-loader and css-loader will convert imported CSS files into CSS-in-JavaScript.

Now to run webpack,

Replace with if you do not want to use react debug tools.

Running this after every change is cumbersome so we can configure webpack to do this automatically.

Start flask in another terminal with

Here is our directory structure after all this setup

Wrap Up

Everything's up and running. If you do not want to run webpack's and flask's development server in different terminals, use can combine them into a single command and the their output's together.

I'm using a Makefile.

So is all I need to start development. When I want a leaner site, without the react debug tools, I can do

GitHub Repo: https://github.com/IceWreck/Flask-React-Boilerplate

Other Pointers:

  • If you are too lazy to press your browser's reload button after an edit then you can configure flask/jinja to load JavaScript from the webpack development server. (requires additional webpack configuration)
  • There are lots of other optimizations you can do for production builds, mentioned in both the React and webpack docs.
  • Do not put anything in the ./static/dist folder as webpack may overwrite it.
  • The webpack config is based on a directory structure I thought was suitable for a simple project, you can change the relative paths to suit your usecase.

I plan to make a second part next week where I will discuss routing and passing data back and forth between flask.

Sorry if this post isn't worded correctly and you don't understand a thing. This is my first time doing technical writing.

Sours: https://dev.to/icewreck/react-flask-integration-part-1-setup-with-webpack-djo
Flask Course - Python Web Application Development



Webpack integration for Flask.

Flask-WebpackExt makes it easy to interface with your existing Webpack project from Flask and does not try to manage Webpack for you. Flask-WebpackExt does this via:

  • Manifests: You tell Webpack to write a using plugins such as webpack-manifest-plugin, webpack-yam-plugin or webpack-bundle-tracker. Flask-WebpackExt reads the manifest and makes your compiled assets available in your Jinja templates.
  • CLI for NPM: Flask-WebpackExt provides a Flask CLI so that e.g. will run in your Webpack project. Similarly, will run .

Optionally you can use Flask-WebpackExt to also:

  • Inject configuration: Flask-WebpackExt will write a into your Webpack project, which you can import in your Webpack configuration. You define what goes in the config e.g. Let Webpack know about output paths or dynamic entry points.
  • Collect bundles: If your Webpack project is spread over multiple Python packages, Flask-WebpackExt can help you dynamically assemble the files into a Webpack project. This is useful if you don’t know until runtime which packages are installed.

Further documentation is available on https://flask-webpackext.readthedocs.io/

User’s Guide¶

This part of the documentation will show you how to get started in using Flask-WebpackExt.

API Reference¶

If you are looking for information on a specific function, class or method, this part of the documentation is for you.

Additional Notes¶

Notes on how to contribute, legal information and changes are here for the interested.

Sours: https://flask-webpackext.readthedocs.io/

Webpack flask

New Webpack Boilerplate Project for Django & Flask


About 1 month ago, I started writing tutorials about and Definitive Guide to Django and Webpack, and I hope it can help people to learn Webpack better because there are not many good tutorials in this area.

After receiving some user feedback, I realize a project is better, because many readers might not have much time to learn how Webpack works. What they want is just a project which can let them quickly write ES6 and SCSS in Django projects.

So I decided to take some time to solve this problem.

My Plan

The boilerplate project should contain two components:

  1. A which has good structure, easy to use and customize. User can create frontend project using , and use it even they have no idea how to config Webpack.
  2. Template tags which can help load Webpack bundle file in the templates, it should be smart to dependency files. (Because Webpack has feature)

Webpack project template

There are some awesome open source Webpack boilerplate projects on Github. After researching, I chose wbkd/webpack-starter because it has all features I need.

And then I did some customization:

  1. I added to the Webpack project, which generate when Webpack compiling. So later I can write to read the to load the entrypoints and the dependency files.
  2. The Webpack project would read entrypoints from a specific directory, so users do not need to edit Webpack config file but just create new files in the directory, which is very convenient

Webpack bundle loader

If you have some experience with Django, then you might hear of . I used it in many projects but also found some problems.

  1. It should read generated by , a create by the same author. It takes time to maintain both and , and the author is now looking for maintainers.
  2. I do not like the API of , and it can not auto load dependency files when loading bundle files.

So I decide to write a new based on , and solve the above problems at once.

Python Webpack Boilerplate

Here is my solution:


Easy to create

This project has a and you can easily create frontend project like this:

$ python manage.py webpack_init # here we use the default frontend slug project_slug [frontend]:

Now you can go to project and run command below:

$ cd frontend $ npm install $ npm run start
  1. The project already supports ES6 and SCSS by default.
  2. You can also import or to it by install extra packages (instructions can be found in the doc)

Webpack Loader

I also created new template tags to help people load Webpack bundle file in template

{% javascript_pack 'app' %}

If the entrypoint has other dependency, the template tag would also load it automatically

For example:

<script type="text/javascript" src="/static/js/runtime.5c7f161e.js" ></script> <script type="text/javascript" src="/static/js/963.225830a8.js" ></script> <script type="text/javascript" src="/static/js/app.c9e79e69.js" ></script>

As you can see, is loaded after dependency js files.

So now in templates we can only focus on the entrypoints without caring about the dependency and this template tag can help you handle it automatically.

You can also import multiple entrypoints in one page like this

{% javascript_pack 'app' 'app2' %}

You can also do the same thing for the css file

{% stylesheet_pack 'app' %}

The API is inspired by rails/webpacker


At first, I build this project for Django community, after I finish the draft version. I realize I can make it also work with Flask to help more people.

I made it work after some hours.

My wish

I have seen many projects use Webpack as frontend solution, but the config and file structures are different. So it is a PAIN to maintain the Webpack, Babel, and other config.

This project can work with both cookiecutter-django and cookiecutter-flask, and the frontend part would have consistent patterns.

Now Django developers and Flask developers can both contribute and help improve this project and make it become better.

And some people who have both Flask projects and Django projects would be happy!

That is why I give it name python-webpack-boilerplate, and I am open to support more Python web frameworks in the future.

Main Features

  • Supports Django and Flask (will support more framework in the future)
  • Automatic multiple entry points
  • Automatic code splitting
  • Hot Module Replacement (HMR)
  • Easy to config and customize
  • ES6 Support via babel (v7)
  • JavaScript Linting via eslint-loader
  • SCSS Support via sass-loader
  • Autoprefixing of browserspecific CSS rules via postcss and autoprefixer
  • Style Linting via stylelint

Project Link


Michael Yin

Michael is a Full Stack Developer from China who loves writing code, tutorials about Django, Wagtail CMS and React.

He has published some ebooks on leanpub and tech course on testdriven.io.

He is also the founder of the AccordBox which provides the web development services.

Sours: https://www.accordbox.com/blog/new-webpack-boilerplate-project-django-flask/
WHAT IS WEBPACK, HOW DOES IT WORK? - Webpack 2 Basics Tutorial


Now discussing:


1732 1733 1734 1735 1736