SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Materials for webpack lecture
Webpack 4
1
Content
2
1 Basic params
2 Practical examples
3 FAQ
Basic params
Webpack
3
npm install webpack webpack-cli --save-dev
webpack
webpack --watch
4
webpack —-mode (developer|production)
5
npm install webpack-dev-server --save-dev
webpack-dev-server --mode development --open
6
webpack —-mode development --config webpack.server.config.js
7
module.exports = {
...
};
const config = {
...
};
module.exports = function(env, options){
return config;
};
8
// entry: string|Array<string>
entry: './path/to/my/entry/file.js'
entry: [
'./path/to/my/entry/file1.js',
'./path/to/my/entry/file2.js'
]
// entry: {[entryChunkName: string]: string|Array<string>}
entry: {
app: './src/app.js',
vendors: './src/vendors.js'
}
9
module.exports = {
output: {
filename: ‘[id].[hash].[chunkhash].[name].js’,
path: '/home/proj/public/assets',
publicPath: ‘http://cdn.example.com/assets/[hash]/',
library: 'MyLibrary',
libraryTarget: ‘umd'
}
};
10
module.exports = {
mode: 'production'
};
11
module.exports = {
plugins: [...]
};
12
[{
test: /.js$/,
use: 'bable-loader',
exclude: '/node_modules/'
},{
test: /.css$/,
use: [
{ loader: 'style-loader' },
{ loader: ‘css-loader', options: { modules: true } }
]
},{
test: /.png/,
use: path.join(__dirname, './src/loaders/base64-loader.js?type=image/png')
}]
13
module.exports = {
target: 'node'
};
14
module.exports = {
context: __dirname
};
15
module.exports = {
devtool: ‘source-map’
};
16
devtool
build
speed
rebuild
speed
prod quality
eval +++ +++ no generated code
cheap-eval-source-map + ++ no
transformed code (lines
only)
cheap-source-map + o yes
transformed code (lines
only)
cheap-module-eval-source-
map
o ++ no original source (lines only)
cheap-module-source-map o - yes original source (lines only)
eval-source-map -- + no original source
module.exports = {
devServer: {
contentBase: './dist',
compress: true,
overlay: true,
hot: true
}
};
17
Practical examples
Webpack
18
{
test: /.(js|jsx)$/,
use: 'babel-loader'
},
{
test: /.(ts|tsx)$/,
use: 'ts-loader'
}
19
{
“compilerOptions": {
"module": "commonjs",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true
},
"exclude": [
"node_modules",
“build"
]
}
20
{
"presets": ["react"]
}
{
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
},
"include": ["transform-es2015-arrow-functions", "es6.map"],
"exclude": ["transform-regenerator", "es6.set"]
}]
]
}
21
{
test: /.(scss|sass|less|styl)$/,
use: [
{ loader: 'style-loader', options: { sourceMap: true } },
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: '(scss|sass|less|stylus)-loader', options: { sourceMap: true } }
]
}
22
modules.exports = {
plugins: {
autoprefixer: {
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'iOS >= 7',
'not ie < 9' // React doesn't support IE8 anyway
],
flexbox: 'no-2009'
}
}
}
23
// webpack-extract-text-plugin@next
plugins: [
new ExtractTextPlugin('style.css')
],
module: {
rules: [
{
test: /.css$/,
use: ExtractTextPlugin.extract({
use: 'css-loader'
})
}
]
}
24
entry: {
'main': [
'./js/main.js',
'./sass/main.scss',
],
'login': './sass/admin/login.scss',
}
25
{
test: /.(jpe?g|png|gif)$/,
loader: 'url-loader',
options: { limit: 10 * 1024 }
},
{
test: /.svg$/,
loader: 'svg-url-loader',
options: { limit: 10 * 1024 }
},
{
test: /.(jpg|png|gif|svg)$/,
loader: 'image-webpack-loader',
enforce: 'pre'
}
26
const ImageminPlugin = require('imagemin-webpack-plugin').default;
plugins: [
new ImageminPlugin({ test: /.(jpe?g|png|gif|svg)$/i })
]
27
{
test: /.(eot|ttf|woff|woff2)$/,
use: 'file-loader'
}
const CopyWebpackPlugin = require('copy-webpack-plugin');
plugins: [
new CopyWebpackPlugin([
{ from: '**/*', to: 'relative/path/to/dest/' }
{ from: '**/*', to: '/absolute/path/to/dest/' }
], options)
]
28
FAQ
Webpack
29
Where to learn more?
https://webpack.js.org/concepts/
https://webpack.js.org/configuration/
https://webpack.js.org/api/
https://webpack.js.org/guides/
https://webpack.js.org/loaders/
https://webpack.js.org/plugins/
https://webpack.js.org/migrate/
https://webpack.js.org/contribute/
30
How to build scss|sass|less|styl ?
{
test: /.(scss|sass|less|styl)$/,
use: [
{ loader: 'style-loader', options: { sourceMap: true } },
{ loader: 'css-loader', options: { sourceMap: true } },
{ loader: 'postcss-loader', options: { sourceMap: true } },
{ loader: '(scss|sass|less|stylus)-loader', options: { sourceMap: true } }
]
}
31
How to reduce weight?
webpack-bundle-analyzer
uglifyjs-webpack-plugin
compression-webpack-plugin
https://bundlephobia.com/
32
How to speed up?
https://webpack.js.org/guides/build-performance/
CommonsChunksPlugin
cache-loader
parallel-webpack
webpack-dev-server
webpack-hot-middleware
webpack-dev-middleware
33
Hot Module Replacement + Redux?
https://webpack.js.org/guides/hot-module-replacement/
https://gist.github.com/markerikson/dc6cee36b5b6f8d718f2e24a249e0491
devServer: {
hot: true
}
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin()
]
34
How to split code into chunks?
https://webpack.js.org/guides/code-splitting/
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
new webpack.optimize.CommonsChunkPlugin({
name: 'common' // Specify the common bundle's name.
})
35
Your plugins/loaders?
https://webpack.js.org/loaders/
https://webpack.js.org/plugins/
https://webpack.js.org/contribute/
https://webpack.js.org/contribute/writing-a-loader/
https://webpack.js.org/contribute/writing-a-plugin/
36
Your plugins/loaders?
class HelloWorldPlugin(){
constructor(options){
this.options = options;
}
apply(compiler){
compiler.plugin('done', function() {
console.log('Hello World!');
});
}
}
module.exports = HelloWorldPlugin;
37
Your plugins/loaders?
module.exports = function loader(src) {
this.cacheable();
const done = this.async();
(new Promise((resolve, reject) => {...}))
.then((result) => done(null, result))
.catch((err) => done(null, 'module.exports = '';'));
};
module.exports.raw = true;
38
Sergei Iastrebov
Senior Software Engineer
sergei-iastrebov
yastrebserdg@yandex.ru
Questions and answers
CrazySquirrel
//goo.gl/peCRwu
39

Weitere ähnliche Inhalte

Was ist angesagt?

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 webpackNodeXperts
 
Bundle your modules with Webpack
Bundle your modules with WebpackBundle your modules with Webpack
Bundle your modules with WebpackJake Peyser
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack IntroductionAnjali Chawla
 
Bundling your front-end with Webpack
Bundling your front-end with WebpackBundling your front-end with Webpack
Bundling your front-end with WebpackDanillo Corvalan
 
Production optimization with React and Webpack
Production optimization with React and WebpackProduction optimization with React and Webpack
Production optimization with React and Webpackk88hudson
 
Once upon a time, there were css, js and server-side rendering
Once upon a time, there were css, js and server-side renderingOnce upon a time, there were css, js and server-side rendering
Once upon a time, there were css, js and server-side renderingAndrea Giannantonio
 
Webpack and Web Performance Optimization
Webpack and Web Performance OptimizationWebpack and Web Performance Optimization
Webpack and Web Performance OptimizationChen-Tien Tsai
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...tdc-globalcode
 
Vue 淺談前端建置工具
Vue 淺談前端建置工具Vue 淺談前端建置工具
Vue 淺談前端建置工具andyyou
 
Advanced front-end automation with npm scripts
Advanced front-end automation with npm scriptsAdvanced front-end automation with npm scripts
Advanced front-end automation with npm scriptsk88hudson
 
One step in the future: CSS variables
One step in the future: CSS variablesOne step in the future: CSS variables
One step in the future: CSS variablesGiacomo Zinetti
 
Bower & Grunt - A practical workflow
Bower & Grunt - A practical workflowBower & Grunt - A practical workflow
Bower & Grunt - A practical workflowRiccardo Coppola
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJSHüseyin BABAL
 
Grunt.js and Yeoman, Continous Integration
Grunt.js and Yeoman, Continous IntegrationGrunt.js and Yeoman, Continous Integration
Grunt.js and Yeoman, Continous IntegrationDavid Amend
 

Was ist angesagt? (20)

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
 
Webpack DevTalk
Webpack DevTalkWebpack DevTalk
Webpack DevTalk
 
Bundle your modules with Webpack
Bundle your modules with WebpackBundle your modules with Webpack
Bundle your modules with Webpack
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack Introduction
 
Bundling your front-end with Webpack
Bundling your front-end with WebpackBundling your front-end with Webpack
Bundling your front-end with Webpack
 
Production optimization with React and Webpack
Production optimization with React and WebpackProduction optimization with React and Webpack
Production optimization with React and Webpack
 
Hey webpack
Hey webpackHey webpack
Hey webpack
 
Once upon a time, there were css, js and server-side rendering
Once upon a time, there were css, js and server-side renderingOnce upon a time, there were css, js and server-side rendering
Once upon a time, there were css, js and server-side rendering
 
Webpack and Web Performance Optimization
Webpack and Web Performance OptimizationWebpack and Web Performance Optimization
Webpack and Web Performance Optimization
 
Webpack
WebpackWebpack
Webpack
 
Webpack
Webpack Webpack
Webpack
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
 
Vue 淺談前端建置工具
Vue 淺談前端建置工具Vue 淺談前端建置工具
Vue 淺談前端建置工具
 
Advanced front-end automation with npm scripts
Advanced front-end automation with npm scriptsAdvanced front-end automation with npm scripts
Advanced front-end automation with npm scripts
 
One step in the future: CSS variables
One step in the future: CSS variablesOne step in the future: CSS variables
One step in the future: CSS variables
 
Angular2 ecosystem
Angular2 ecosystemAngular2 ecosystem
Angular2 ecosystem
 
Bower & Grunt - A practical workflow
Bower & Grunt - A practical workflowBower & Grunt - A practical workflow
Bower & Grunt - A practical workflow
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Grunt.js and Yeoman, Continous Integration
Grunt.js and Yeoman, Continous IntegrationGrunt.js and Yeoman, Continous Integration
Grunt.js and Yeoman, Continous Integration
 

Ähnlich wie Lecture: Webpack 4

Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoJavier Abadía
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development toolsSimon Kim
 
Richard Fridrich: Třesení stromem v JavaScriptu
Richard Fridrich: Třesení stromem v JavaScriptuRichard Fridrich: Třesení stromem v JavaScriptu
Richard Fridrich: Třesení stromem v JavaScriptuDevelcz
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!David Gibbons
 
How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?Tomasz Bak
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applicationsAstrails
 
«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​FDConf
 
От экспериментов с инфраструктурой до внедрения в продакшен
От экспериментов с инфраструктурой до внедрения в продакшенОт экспериментов с инфраструктурой до внедрения в продакшен
От экспериментов с инфраструктурой до внедрения в продакшенDmitry Makhnev
 
The hitchhiker's guide to the Webpack - Sara Vieira - Codemotion Amsterdam 2017
The hitchhiker's guide to the Webpack - Sara Vieira - Codemotion Amsterdam 2017The hitchhiker's guide to the Webpack - Sara Vieira - Codemotion Amsterdam 2017
The hitchhiker's guide to the Webpack - Sara Vieira - Codemotion Amsterdam 2017Codemotion
 
Code Splitting in Practice - Shanghai JS Meetup May 2016
Code Splitting in Practice - Shanghai JS Meetup May 2016Code Splitting in Practice - Shanghai JS Meetup May 2016
Code Splitting in Practice - Shanghai JS Meetup May 2016Wiredcraft
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridGiorgio Cefaro
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrideugenio pombi
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slidesharetomcopeland
 
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Codemotion
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Luciano Mammino
 
WEBPACK
WEBPACKWEBPACK
WEBPACKhome
 
JavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and FutureJavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and FutureIgalia
 
Rails Engine | Modular application
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular applicationmirrec
 
Webpack Encore - Asset Management for the rest of us
Webpack Encore - Asset Management for the rest of usWebpack Encore - Asset Management for the rest of us
Webpack Encore - Asset Management for the rest of usStefan Adolf
 

Ähnlich wie Lecture: Webpack 4 (20)

Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development tools
 
Richard Fridrich: Třesení stromem v JavaScriptu
Richard Fridrich: Třesení stromem v JavaScriptuRichard Fridrich: Třesení stromem v JavaScriptu
Richard Fridrich: Třesení stromem v JavaScriptu
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
Browserify
BrowserifyBrowserify
Browserify
 
How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
 
«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​
 
От экспериментов с инфраструктурой до внедрения в продакшен
От экспериментов с инфраструктурой до внедрения в продакшенОт экспериментов с инфраструктурой до внедрения в продакшен
От экспериментов с инфраструктурой до внедрения в продакшен
 
The hitchhiker's guide to the Webpack - Sara Vieira - Codemotion Amsterdam 2017
The hitchhiker's guide to the Webpack - Sara Vieira - Codemotion Amsterdam 2017The hitchhiker's guide to the Webpack - Sara Vieira - Codemotion Amsterdam 2017
The hitchhiker's guide to the Webpack - Sara Vieira - Codemotion Amsterdam 2017
 
Code Splitting in Practice - Shanghai JS Meetup May 2016
Code Splitting in Practice - Shanghai JS Meetup May 2016Code Splitting in Practice - Shanghai JS Meetup May 2016
Code Splitting in Practice - Shanghai JS Meetup May 2016
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshare
 
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
 
WEBPACK
WEBPACKWEBPACK
WEBPACK
 
JavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and FutureJavaScript Modules Past, Present and Future
JavaScript Modules Past, Present and Future
 
Rails Engine | Modular application
Rails Engine | Modular applicationRails Engine | Modular application
Rails Engine | Modular application
 
Webpack Encore - Asset Management for the rest of us
Webpack Encore - Asset Management for the rest of usWebpack Encore - Asset Management for the rest of us
Webpack Encore - Asset Management for the rest of us
 

Kürzlich hochgeladen

PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 

Kürzlich hochgeladen (20)

PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 

Lecture: Webpack 4

Hinweis der Redaktion

  1. Good evening, everybody. Today we going to talk about the Webpack.
  2. First of all, we'll talk about basic parameters for webpack version 4. Then, we'll take a look at some practical examples. After that, I'll answer some of your questions from the tech chat. And at the end you'll receive additional materials and will be able to ask some questions.
  3. Let's start with the main differences and settings of webpack version 4
  4. First thing that you’ll see when using a new webpack is that it can work without any configuration file. Simply install the webpack and it console utility, and it's ready to go. You can just call webpack and it'll try to take index.js file from src folder as an entry point and compile it into dist. In order to start webpack in a tracking mode, you needs to pass -watch parameter, then webpack will monitor file changes and re-build them.
  5. Next great innovation of version 4 is mode. If earlier we passed NODE_ENV and set up what plugins and other things to use, now we can call webpack with the flag -mode developer or production and it'll apply the built-in settings. About, what is included in which mode you can read in documentation. In general, production mode focuses on compression and optimization, while developer mode focuses on debugging and development speed.
  6. Further, it can be useful for you during development to use the webpack-dev-server. In fact, it's webpack with an express server wrapper, which can be run as well as usual webpack, but in addition to building and tracking files, it runs a development server, track changes and upload files on fly. We'll talk later about what settings you can set for webpack-dev-server. Now I want to draw your attention to the parameter -open which tells webpack-dev-server that at start it's necessary not only to start the dev server, but also to open browser at that address at which this server was started. You should take into account that when webpack-dev-server working the data, which it display in the browser, are stored in the memory and not written on disk.
  7. Use webpack without settings kinda fun, but not very effective. So let's add options for webpack. To do this we need to create a file with the name webpack.config.js, which will be used as the default file. Since there can be several webpack configuration files (for the client and server, for prod and dev and etc.), you can specify which file to use with the —config parameter.
  8. The webpack.config.js is a regular js file from which we export an object with parameters for wepback as in previous versions, but in version 4 there is another way to export config as a function. If we export config as a function, there will be two parameters passed to this function when calling webpack. - env - this's the environment settings - options - this's options which were caused by webpack In env there will be a variable NODE_ENV (if we set it), and in options there will be mode equal to development or production. Based on these variables, we can somehow adjust webpack parameters for different build modes. Let's now look at the options in a detail.
  9. The first required parameter for webpack is entry, if you do not use it in conjunction with gulp. As value entry can take a string, an array of strings, or an object with keys as chunk names and values as string or array of strings. The first variant of entry as string or array of strings is similar to setting object with a single key and passing that string or strings to it. In entry variant as an object, each property are separate chunk that will be written to separate file. At the same time, if an array is passed as a value, the values of these files will be combined and written as one file. The most common variant of entry is as a key value form with a single string as value.
  10. The output parameters is for output files configuration. If you don't specify it, everything will be written to the index.js file in dist. if you want to override this or if you have multiple chunks, you need to set file names. File name specifies which mask to use for output file name. In addition to the normal characters it's possible to use several variables, such as: - id - this's a chunk id; - hash - this's a module hash, - chunkhash - this's a chunk hash, - name - this's a name of the chunk and etc. Among other things, you can override the directory in which output files will be written (by default it's dist), but if you set path, you can specify in which folder to write. You should remember that in the webpack settings almost all paths are written from root, to write relative paths you can use nodejs module path.resolve. If you are using webpack-dev-server, you must specify publicPath. What you specify in this parameter will be used as a prefix for the dev server when it searching for files, as well as a prefix for asynchronously loaded chunks. Two more parameters which will be useful for you, if you do external library, it’s a library, in which you write the name of the library, and a libraryTarget, which indicate how your library will connect to others. You can specify it to commonjs, commonjs2, amd, var or umd option, which says that the library can be loaded via AMD, CommonJS2 or root.
  11. Let's talk a little more about mode parameter. As you have already seen, it can be passed through the console arguments, but mode can also be set in the configuration file. Almost all console settings for webpack can be set through a configuration file. When you enable a particular mode, different plugins adding in webpack and they start working in a different mode. If mode is not set, everything works by default. You can read more information about mods in the documentation.
  12. The next small parameter is plugins, where you can pass an array of used plugins. By comparison with the previous version, you need to pass less plugins since many of them are passed under the hood depending on mode.
  13. Now let's move on to the main part of webpack settings, namely loaders. Loaders is specified in the module rules part as an array of objects. Each object contains the keyword test in which is written a regular expression for matching files. You can also write an exclude property in which you can pass a string or an array of strings that will be used as masks to exclude some files from the scan. Among other things, the keyword use is used to pass one loader or an array of objects. Loaders can also accept additional parameters via the options parameter. You can also use your own loaders, to do this you can use npm packages, or use the full path to the JS loader file in loader parameter.
  14. Next parameters is target. Target allows you to specify for which system you building your scripts. You can specified it to web or node. Depending on the values wepback will use a variety of building environment.
  15. The context parameter allows you to specify the root folder of the project relative to which all other paths will be resolved. If you specify context, all paths in entry, output or loaders will be considered relative to this specified folder.
  16. Devtool option allows you to specify whether to generate a sourcemap or not. You should use it mostly in the development mode, to make it easier debugging. You can also use it in the production, but again, only for debugging. Here are the different options for generating sourcemap. For dev mode, the most convenient is eval, since it's provide really fast build and re-build. For production, you can use source-map mode, in which source maps will be generated as separate files. In this case, link will be added in each file, which will load the sourcemap file only when the devtools panel is open.
  17. The last thing we'll look at from the main settings is the settings for dev server. - contentBase tells you which folder to use as the root folder - compress indicates whether to compress files for browser - overlay overrides how build errors are reported. without this options, they will be displayed simply in console, and with overlay flag set, they will appear on top of the page, which can be somewhat useful - hot options used to specify that you want to reload files on fly without reloading whole page.
  18. The rest information you can see in the documentation, because you can configure a lot, but most things work fine by default or need in a very specific cases and remember them is not so helpful. Better look in the documentation if necessary, than to keep all this in mind. Let's now look at practical examples, how to configure webpack to build different files. The examples will have many different loaders and plugins with references to their documentations. Some basic examples you'll see now, and for more you'll have to go to documents for the same reason as with webpack documentation.
  19. Let's start with what webpack is usually used for. You can simply use babel or JS or JSX files and ts-loader for TS or TSX. About ts-loader, you can find others loaders for typescript, but this one I used on a big project and at that time I didn't find any better solution, maybe now you can use something better.
  20. All settings for TypeScript are written in taconfig.json file. Approximately the file for ts-loader for React project can look like this. We say that our modules will be loaded through commonjs, that our code should be transpiled in es5 and that our library written on es6. Also we say that we use dom and react, that we need source maps and etc.
  21. For babel, the settings should be stored in a .babelrc file. That is how looks a simple babel config for React. And below is an example of more complex settings for some js project, in which we specify that code should work under the last two versions of the main browsers and safari since version 7. Plus we say that we going to use arrow functions and Map, but we don't need polyfill for generators or Set.
  22. The next thing you'll probably want to build on wepback is styles. This could be a regular css, scss, sass, less, styl or something else, but the build scheme would be roughly the same. From the bottom up, you connect the loader for the language in which you have styles, then you can add postcss for autofix or some other style polyfill, then there is the main loader and then style-loader, which will pack your styles inside js. With this scheme, you import styles as a normal js file in project and they'll arrive inside js, and then, thanks to style-loader, they'll be dynamically written to the head in the form of a style tag. If you need sourcemap for styles, you should pass sourceMap option in each loader.
  23. Let's talk about postcss. You can write settings for it in webpack config file in loader options or you can write them in postcss.config.js file. This is an example of postcss.config.js with some settings for autoprefixer and flexbox. You can read about postcss, available plugins and settings for it in documents.
  24. Going back to styles and style-loader, it may be convenient to collect css directly in js and deliver it together, but sometimes it can be useful to collect css into separate bundles. This can be done with webpack-extract-text-plugin. It is used approximately like this, we add plug-in and loader where we specify that for styles we want to use ExtractTextPlugin, and then we specify what loader we want to use inside of it. Thus, we can use files of various formats in the project, and collect them into separate bundles. You can see how to set up several different exports and what else ExtractTextPlugin can do in the documentation.
  25. Other interesting thing in a new webpack is that you can use other files as an entry point, not just js. You'll probably need to use ExtractTextPlugin or something like that, but overall, You can try to use it in your project.
  26. Another thing that you can do in webpack is optimize images. So small jpg png and gif can be linearized with url-loader, and svg with svg-url-loader. Also you can optimize all images with image-webpack-loader by setting loader with enforce: 'pre' options, which will tell webpack that this loader should be used before regular loaders.
  27. Also you can optimise images in a new webpack version by using imagemin-webpack-plugin. In base case it can be used like this. For additional options look to the documentation.
  28. For the remaining files, the most common thing to do is to simply copy them from src folder to dist folder. Previously, this was done by using file-loader, and now you can use copy-webpack-plugin.
  29. That's basically it. For additional information you can go to documentations. And now let's look at your questions from technical chat.
  30. Where to learn more? concepts - this's what we have been passed; this's an initial level configuration - this's a bit more advanced webpack settings api - there is a very deep way to set options in webpack guides - there is the same as the previous three links, but in step by step format loaders/plugins - this is the reference for guidance for leaders and plugins; there you can find existing loaders plugins and documentation for them; and it's better to take a look in there before you start to write something by yourself migrate - you probably won't need it, but it's a little help with migration from older versions contribute - this is how to write something by yourself for webpack and share with community
  31. How to build scss | sass | less | styl ? We have already talked about that. Just use loaders for your language and that's it.
  32. How to reduce weight? You can try to dig around in the settings and play with uglifyjs, but rather it's better to look at the project, for example, by using the webpack-bundle-analyzer. This plugin will build a graph of dependencies and module sizes and it'll be possible to understand what can be thrown out to make project lighter. If you need to use something, try to find several solutions and compare them by important indicators, including size.
  33. How to speed up? The question is not trivial, as well as wight one. In general, you can read about speed configuration there. In short, you can: - break a code into chunk using CommonsChunksPlugin - run on multiple processors, for example, using parallel-webpack, webpack-dev-server, webpack-hot-middleware or webpack-dev-middleware.
  34. Hot Module Replacement + Redux? If anyone doesn't know, Hot Module Replacement is such options of webpack to replace files during the development without reloading the entire page. More details about it can be found here. In general, it's quite simple to turn on, by using hot parameter for devServer settings and a couple of plugins. It's also possible to make it work with redux. To do so you need to fix store and main component a little bit. And how to do this you can read in a second link.
  35. How to split code into chunks? Code can be automatically split into chunk by the frequency. To do this we need to add chunkFilename options and CommonsChunkPlugin. For additional information read documentations,
  36. Your plugins/loaders? First, most likely you don't need to write any of them by yourself, check the first two links. Second, if you really need to write something, check the last three links.
  37. In short, plugin is a regular js, where we export some class with constructor and apply method. When it's working, the compiler will be passed as a parameter for apply method. You can subscribe for different events of compiler and make some changes, but it's better to read documentation about it, because there're many things that you can do in plugin,
  38. Loaders are written just as easily. We export a function that will take in src the path of the downloaded file and the context. You can use different methods from context, for example, cacheable says that the result of this loader can be reused, and if there are multiple connections, or if the file has not changed since the last loading, the data can be taken from the cache. Async returns a callback that should be called after the loader is done and it should be passed module.exports = ‘'; because leader must return the js modules. It's useful to wrap loader code in promises. If your loader return some text data or base64, you need to specify the export flag.row, otherwise webpack will try to read and use result of this loader as js.
  39. That's it, here are some link with a set of materials that can be useful for you. You can read more about webpack in the documentation. And now you can ask some additional questions.