React & Webpack - Project set up for multi page application - javascript

I'm starting up a react project (using create-react-app) which will have multi "one page" components within. So, I assume, the directory structure for development would look like below:
/Project
/node_modules
/public
/src
/components
/layout
/popup
...
/pages
/dashboard
index.js
/profiles
index.js
...
If I build the project without any modification, it would bundle all the source code and resources under one directory. Well, that's not going to work for what I am trying to do for this project. I need to have different bundles for each page. So the bundles under the /public folder should look something similar to the following structure:
/Project
...
/build
/dashboard
/static
/css
/js
/media
index.html
/profiles
/static
/css
/js
/media
index.html
...
I looked at "Code Splitting" in webpack documentation. There's a good example with different entry points but I couldn't adapt it. How can I achieve the desired setup with webpack and react?

I would suggest to use React code splitting, using React Loadable, no need to modify Webpack configuration.
https://reactjs.org/docs/code-splitting.html

May be it is late to answer but I was facing the same issue and found a simple solution that I wanted to share.
I followed these steps:
Multiple entry points in webpack for each page
dynamic output bundle names for each entry point
Multiple html output files with different filenames using HtmlWebpackPlugin, also define particular chunks (bundles),
new HtmlWebpackPlugin({ filename: 'index.html',template: './src/index.html' ,chunks:['page1']})
Each template for each html page will have one div with particular id lets say root which is used by react app to render its app on dom.
Now every js entry point for each page will have
ReactDOM.render(<Page1 />, document.getElementById("root"));

Have a look at the Webpack docs on Multiple Entry files
And have a look at the examples in webpack's github

Related

Basic Python Web application giving jinja2 error [duplicate]

I am trying to render the file home.html. The file exists in my project, but I keep getting jinja2.exceptions.TemplateNotFound: home.html when I try to render it. Why can't Flask find my template?
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
/myproject
app.py
home.html
You must create your template files in the correct location; in the templates subdirectory next to the python module (== the module where you create your Flask app).
The error indicates that there is no home.html file in the templates/ directory. Make sure you created that directory in the same directory as your python module, and that you did in fact put a home.html file in that subdirectory. If your app is a package, the templates folder should be created inside the package.
myproject/
app.py
templates/
home.html
myproject/
mypackage/
__init__.py
templates/
home.html
Alternatively, if you named your templates folder something other than templates and don't want to rename it to the default, you can tell Flask to use that other directory.
app = Flask(__name__, template_folder='template') # still relative to module
You can ask Flask to explain how it tried to find a given template, by setting the EXPLAIN_TEMPLATE_LOADING option to True. For every template loaded, you'll get a report logged to the Flask app.logger, at level INFO.
This is what it looks like when a search is successful; in this example the foo/bar.html template extends the base.html template, so there are two searches:
[2019-06-15 16:03:39,197] INFO in debughelpers: Locating template "foo/bar.html":
1: trying loader of application "flaskpackagename"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /.../project/flaskpackagename/templates
-> found ('/.../project/flaskpackagename/templates/foo/bar.html')
[2019-06-15 16:03:39,203] INFO in debughelpers: Locating template "base.html":
1: trying loader of application "flaskpackagename"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /.../project/flaskpackagename/templates
-> found ('/.../project/flaskpackagename/templates/base.html')
Blueprints can register their own template directories too, but this is not a requirement if you are using blueprints to make it easier to split a larger project across logical units. The main Flask app template directory is always searched first even when using additional paths per blueprint.
I think Flask uses the directory template by default. So your code should be like this
suppose this is your hello.py
from flask import Flask,render_template
app=Flask(__name__,template_folder='template')
#app.route("/")
def home():
return render_template('home.html')
#app.route("/about/")
def about():
return render_template('about.html')
if __name__=="__main__":
app.run(debug=True)
And you work space structure like
project/
hello.py
template/
home.html
about.html
static/
js/
main.js
css/
main.css
also you have create two html files with name of home.html and about.html and put those files in templates folder.
If you must use a customized project directory structure (other than the accepted answer project structure),
we have the option to tell flask to look in the appropriate level of the directory hierarchy.
for example..
app = Flask(__name__, template_folder='../templates')
app = Flask(__name__, template_folder='../templates', static_folder='../static')
Starting with ../ moves one directory backwards and starts there.
Starting with ../../ moves two directories backwards and starts there (and so on...).
Within a sub-directory...
template_folder='templates/some_template'
I don't know why, but I had to use the following folder structure instead. I put "templates" one level up.
project/
app/
hello.py
static/
main.css
templates/
home.html
venv/
This probably indicates a misconfiguration elsewhere, but I couldn't figure out what that was and this worked.
If you run your code from an installed package, make sure template files are present in directory <python root>/lib/site-packages/your-package/templates.
Some details:
In my case I was trying to run examples of project flask_simple_ui and jinja would always say
jinja2.exceptions.TemplateNotFound: form.html
The trick was that sample program would import installed package flask_simple_ui. And ninja being used from inside that package is using as root directory for lookup the package path, in my case ...python/lib/site-packages/flask_simple_ui, instead of os.getcwd() as one would expect.
To my bad luck, setup.py has a bug and doesn't copy any html files, including the missing form.html. Once I fixed setup.py, the problem with TemplateNotFound vanished.
I hope it helps someone.
Check that:
the template file has the right name
the template file is in a subdirectory called templates
the name you pass to render_template is relative to the template directory (index.html would be directly in the templates directory, auth/login.html would be under the auth directory in the templates directory.)
you either do not have a subdirectory with the same name as your app, or the templates directory is inside that subdir.
If that doesn't work, turn on debugging (app.debug = True) which might help figure out what's wrong.
I had the same error turns out the only thing i did wrong was to name my 'templates' folder,'template' without 's'.
After changing that it worked fine,dont know why its a thing but it is.
You need to put all you .html files in the template folder next to your python module. And if there are any images that you are using in your html files then you need put all your files in the folder named static
In the following Structure
project/
hello.py
static/
image.jpg
style.css
templates/
homepage.html
virtual/
filename.json
When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :
the file does not exist or
the templates folder does not exist
Create a folder with name templates in the same directory where the python file is located and place the html file created in the templates folder.
Another alternative is to set the root_path which fixes the problem both for templates and static folders.
root_path = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).parent
app = Flask(__name__.split('.')[0], root_path=root_path)
If you render templates directly via Jinja2, then you write:
ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)
After lots of work around, I got solution from this post only,
Link to the solution post
Add full path to template_folder parameter
app = Flask(__name__,
template_folder='/home/project/templates/'
)
My problem was that the file I was referencing from inside my home.html was a .j2 instead of a .html, and when I changed it back jinja could read it.
Stupid error but it might help someone.
Another explanation I've figured out for myself
When you create the Flask application, the folder where templates is looked for is the folder of the application according to name you've provided to Flask constructor:
app = Flask(__name__)
The __name__ here is the name of the module where application is running. So the appropriate folder will become the root one for folders search.
projects/
yourproject/
app/
templates/
So if you provide instead some random name the root folder for the search will be current folder.

How index.js file is able to communicate with index.html?

In React project both index.html and index.js file are inside different folder and there is no link in between these two file. Then how we are able target div whose id is root of HTML file by
using document.getElementById("root") inside index.js file.
please answer this in easy language because i have just start learning this , I am compeletly begineer.
React is one of the best JS libraries out there. It simplifies the development process without cluttering the implementation details explicitly. The index.html and index.js get linked during runtime when you start the script. React uses webpack under the hood where the entry for the webpack is index.js and when it is run(after all the conversions) it injects the javascript code in the HTML file which is index.html. And you can see this injected code in the index.html when you build the bundle inside the build folder.

How to load packages installed by `bundle` in webpack?

In a Ruby on Rails application, how can we require or import a package which was not installed via npm or yarn, but via bundle?
I tried:
//= require package-name
But that doesn't seem to work with webpacker.
require("package-name") doesn't work either (because it is not found in node_modules).
For normal Rails environment, you can use normal directory path if you want to require some files.
Suppose your assets folder looks like this
├── application.js
└── something.js
and you want to require something.js then you just need to write
//= require ./something.js
to your application.js
For a package that you manually place somewhere, then you have to add the place of packages to Rails.application.config.assets.paths
If you are using Rails v5, you can check the config/initializers/assets.rb to see the magic of loading node_modules happened
I have no webpack experience and no solution for your problem.
what about this
https://webpack.js.org/loaders/bundle-loader/
as I read in the documentation paths chapter
Paths
By default, Webpacker ships with simple conventions for where the JavaScript app files and compiled webpack bundles will go in your Rails app, but all these options are configurable from config/webpacker.yml file.
The configuration for what webpack is supposed to compile by default rests on the convention that every file in app/javascript/packs/*(default) or whatever path you set for source_entry_path in the webpacker.yml configuration is turned into their own output files (or entry points, as webpack calls it). Therefore you don't want to put anything inside packs directory that you do not want to be an entry file. As a rule of thumb, put all files you want to link in your views inside "packs" directory and keep everything else under app/javascript.
Suppose you want to change the source directory from app/javascript to frontend and output to assets/packs. This is how you would do it:
# config/webpacker.yml
source_path: frontend
source_entry_path: packs
public_output_path: assets/packs # outputs to => public/assets/packs
Similarly you can also control and configure webpack-dev-server settings from config/webpacker.yml file:
# config/webpacker.yml
development:
dev_server:
host: localhost
port: 3035
If you have hmr turned to true, then the stylesheet_pack_tag generates no output, as you will want to configure your styles to be inlined in your JavaScript for hot reloading. During production and testing, the stylesheet_pack_tag will create the appropriate HTML tags.
The asset-pipeline loads the files from the path defined with Rails.application.config.assets.paths
This is the output from my rails console
["/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/config",
"/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/images",
"/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/javascripts",
"/home/fabrizio/Documents/Sublime/Rails/surfcheck/app/assets/stylesheets",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/font-awesome-rails-4.7.0.2/app/assets/fonts",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/font-awesome-rails-4.7.0.2/app/assets/stylesheets",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/jquery-rails-4.3.1/vendor/assets/javascripts",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/coffee-rails-4.2.2/lib/assets/javascripts",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/actioncable-5.1.4/lib/assets/compiled",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/actionview-5.1.4/lib/assets/compiled",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/turbolinks-source-5.0.3/lib/assets/javascripts",
#<Pathname:/home/fabrizio/Documents/Sublime/Rails/surfcheck/node_modules>,
#<Pathname:/home/fabrizio/Documents/Sublime/Rails/surfcheck/vendor>,
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/stylesheets",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/javascripts",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/fonts",
"/home/fabrizio/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/bootstrap-sass-3.3.7/assets/images"]
When you do a require in your application.js or application.scss, sprockets will use the ruby require statement to search that file in the predefined paths.
In case of a GEM, it will find it in the .rbenv/version/yourversion folder.
My approach to solve this problem would be to include those files from the gem that you need for you front end app in the correct folder, so just visit the repository from the GEM and copy paste those file in the correct location.
I know this is not a solution to your problem, but I just wanted to help you out.
Bye
Fabrizio

How do I link to Bootstrap 4 and its scripts?

According to this blog (which is written for BS3), I should add the following lines to the angular.cli.json file.
...
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js"
],
...
The problem is that in the distribution I'm using (BS4 Alpha 6), there's no such file. In the dist directory, there's a bunch of files as follows.
alert.js
button.js
carousel.js
collapse.js
dropdown.js
modal.js
popover.js
scrollspy.js
tab.js
tooltip.js
util.js
Do I have to link to them each individually? Am I missing a minified file somewhere? I'm in dist so I assumed that it's the production version.
Should I go about it in a totally different way, perhaps? I'm trying the Angular CLI package since I want to test without Gulp, Grunt nor Webpack. Is there an approach where I can include, reqest, demand or append those file (preferably minified) to my web site?
The styles I've included my simply importing what I needed from the dist like this.
#import "~bootstrap/dist/css/bootstrap.min.css";
However, I'm a bit confused on how to handle JS of the BS.
You're looking in the wrong place.
The files you are seeing are in js/dist/. You should be looking in dist/js/.

How to uglify the assets for static html and bundle js at one go using webpack?

I have a homepage(index.html) which is a static html with its assets, and after user login at the homepage, it will go to the second page(home.html) which is a react app.
My folder structure is like this:
--build/
----index.html
----home.html
----home.bundle.js
----assets/
------index.css
------index.js
--src/
----static/
------index.html
------home.html
------assets/
--------homepage.css
--------homepage.js
----components/
------home.js
I want to use webpack to :
1. minify the assets of index.html
2. bundle the index.js app.
My questions are:
1. What about I bundle all the assets of index.html rather than just uglify? Is this a better approach?
2. How to use Webpack to fulfill the above 2 requirements? I know how to bundle a pure SPA but don't know how to deal with this mixed type.
Thanks
You can't uglify an html file (otherwise i will learn something today ;-)) but you can uglify your javascript to reduce the size and allow a better performance when they re loaded in the browser.
So what you can do for starting, it is too bundle all your javascript in one bundle file that you will insert manually in your html file. You can do it because in general we give a static name (e.g bundle.js) for the bundle generated by webpack.
Hope that s answering your question?
Romain

Categories