Professional Documents
Culture Documents
We’re not taking advantage of the fact that the browser can cache scripts when they are
not changed. This not only affects the development process, but even in production, users will not have
the optimum experience.
A better alternative is to have two bundles, one for the application code and another
for all the libraries. It turns out that a plugin called CommonsChunkPlugin, a webpack
built-in plugin, can do this quite easily.
module.exports = {
entry: './src/App.jsx',
entry: {
app: './src/App.jsx',
vendor: ['react','react-dom','whatwg-fetch'],
},
output: {
path: './static',
filename: 'app.bundle.js'
},
plugins: [
new
webpack.optimize.CommonsChunkPlugin('vendor','vendor.bun
dle.js')
],
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: ['react','es2015']
}
},
WebPack Server as Proxy
• devServer: { },
• port: 8000,
• contentBase: 'static',
• proxy: {
• '/api/*': {
• target: 'http://localhost:3000'
•}
Hot module replacement
• To enable HMR, all we have to do is add a couple of command line parameters to the webpack-dev-server
invocation:
node_modules/.bin/webpack-dev-server --hot –inline
• import React from 'react';
• import ReactDOM from 'react-dom';
• import IssueList from './IssueList.jsx';
• const contentNode = document.getElementById('contents');
• ReactDOM.render(<IssueList />, contentNode); // Render the component inside
• the content Node
• if (module.hot) {
• module.hot.accept();
• }
HMR as MiddleWare
• The way to do this is to install HMR as middleware in the Express server. As As
• discussed earlier, middleware is something that can intercept requests and do some
• special processing. The webpack-dev-middleware does the same work as it did as an
• independent webpack-dev-server: it looks for changes to files, and blocks requests to
the
• bundle until the changes are incorporated into the bundle. The webpack-hot-middleware
• does a similar thing for HMR. Let’s make these two middleware functions available by
• installing the respective modules:
• $ npm install --save-dev webpack-dev-middleware webpack-hot-middleware
few changes to the configuration for it to be used in an HMR environment. They are the
following:
• In the Application
• The following steps allow modules to be swapped in and out of an
application:
1.The application asks the HMR runtime to check for updates.
2.The runtime asynchronously downloads the updates and notifies the
application.
3.The application then asks the runtime to apply the updates.
4.The runtime synchronously applies the updates.
• You can set up HMR so that this process happens automatically, or you
can choose to require user interaction for updates to occur.
How It Works
• In the Compiler
• In addition to normal assets, the compiler needs to emit an "update" to allow
updating from the previous version to the new version. The "update" consists of
two parts:
1.The updated manifest (JSON)
2.One or more updated chunks (JavaScript)
• The manifest contains the new compilation hash and a list of all updated chunks.
Each of these chunks contains the new code for all updated modules (or a flag
indicating that the module was removed).
• The compiler ensures that module IDs and chunk IDs are consistent between
these builds. It typically stores these IDs in memory (e.g. with
webpack-dev-server), but it's also possible to store them in a JSON file.
How It Works
• In a Module
• HMR is an opt-in feature that only affects modules containing HMR code. One example
would be patching styling through the style-loader. In order for patching to work, the
style-loader implements the HMR interface; when it receives an update through HMR, it
replaces the old styles with the new ones.
• Similarly, when implementing the HMR interface in a module, you can describe what
should happen when the module is updated. However, in most cases, it's not mandatory
to write HMR code in every module. If a module has no HMR handlers, the update
bubbles up. This means that a single handler can update a complete module tree. If a
single module from the tree is updated, the entire set of dependencies is reloaded.
• See the HMR API page for details on the module.hot interface.
How it Works
• In the Runtime
• Here things get a bit more technical... if you're not interested in the internals, feel free to jump to the HMR API page or HMR guide.
• For the module system runtime, additional code is emitted to track module parents and children. On the management side, the
runtime supports two methods: check and apply.
• A check makes an HTTP request to the update manifest. If this request fails, there is no update available. If it succeeds, the list of
updated chunks is compared to the list of currently loaded chunks. For each loaded chunk, the corresponding update chunk is
downloaded. All module updates are stored in the runtime. When all update chunks have been downloaded and are ready to be
applied, the runtime switches into the ready state.
• The apply method flags all updated modules as invalid. For each invalid module, there needs to be an update handler in the module
or in its parent(s). Otherwise, the invalid flag bubbles up and invalidates parent(s) as well. Each bubble continues until the app's entry
point or a module with an update handler is reached (whichever comes first). If it bubbles up from an entry point, the process fails.
• Afterwards, all invalid modules are disposed (via the dispose handler) and unloaded. The current hash is then updated and all accept
handlers are called. The runtime switches back to the idle state and everything continues as normal.
Serverside webpack &
Debugging
• Middle approach is somewhat challenge.
• Use some babel present comments in the command line depending
on node version.
• webpack.config.js: Add Source Map Configuration
devtool: 'source-map'
ESLINT
• A linter (something that lints) checks for suspicious code that may be
a bug. It can acheck whether your code adheres to conventions and
standards that you want to follow across your team to make the code
predictably readable.
• $ npm install --save-dev eslint-config-airbnb
. .eslintrc: Default .eslintrc File Contents
{
"extends": "airbnb"
}
ESLint Features
• SyStem Environment
• Syntax consistency(missing semicolon,paranthesis..)
• Editing conveniences(require curly braces after if statement)
• Structural Issues(variables should be defined before using)
• React Specifics
• Rules overrides
Unit -V
React Server Side Rendering
Server Side Rendering(SSR)
• Server−side rendering has been around for a while now. It was first
introduced in the early 2000s and has been used by many websites
since then.
• // server/index.js
• const express = require('express');
• const app = express();
• const PORT = process.env.PORT || 3001;
• app.listen(PORT, () => {
• console.log(`Server is listening on port ${PORT}`);
• });
• In this code snippet, we create an Express app and start listening on port 3001.
Building React Components for SSR
• Now, let's create a simple React component to render on the server. In the src folder, create a new file called AppServer.js.
This component will be the server-rendered version of our application.
• // src/AppServer.js
• import React from 'react';
• const AppServer = () => {
• return (
• <div>
• <h1>Hello from Server-Side Rendered React App!</h1>
• </div>
• );
• };
Setting up Webpack for SSR
Now, add a new script to your package.json file to build the server-side bundle:
"scripts": {
...
"build:server": "webpack --config webpack.server.js"
}
Rendering the React Component on the Server
• With the Webpack configuration in place, it's time to render the React
component on the server. First, build the server-side bundle by
running the following command:
// server/index.js
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const AppServer = require('../src/AppServer').default;
res.send(html);
});
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
In this file, we import the AppServer component, use ReactDOMServer.renderToString() to convert it
into an HTML string, and send the generated HTML to the client.
"scripts": {
...
"start:server": "node build/server.js"
}
To start the server, run the following command: