คู่มือการใช้งาน Webpack ฉบับ YoProgrammer
- Init Webpack
- Build Webpack
- Watch Webpack
- Loader
- Babel(es2015)
- Minification
- Sass
- Extract
- Relative URL
- Purify CSS
- Long-Term Caching
- Optimization Image
- Manifests
- HTML TEMPLATE
- Webpack Define Plugin
- Extract Text Plugin
- Copy Webpack Plugin
- Image Webpack Loader
- Vendor Splitting
- Provide Plugin
- Source Map
npm init -y
npm install webpack --save-dev
ทดสอบเรียก webpack พิมพ์คำสั่ง webpack
ผลลัพธ์
No configuration file found and no output filename configured via CLI option.
A configuration file could be named 'webpack.config.js' in the current directory.
Use --help to display the CLI options.
webpack src/main.js dist/bundle.js
webpack src/main.js dist/bundle.js --watch
เพิ่ม script เพื่อ run command ที่ package.json ดังนี้
"scripts": {
"build": "webpack src/main.js dist/bundle.js",
"watch": "npm run build -- --watch"
},
สร้างไฟล์ webpack.config.js touch webpack.config.js
โดยโครงสร้างคร่าวๆ เริ่มต้นจะประกอบด้วย
const path = require('path')
module.exports = {
entry: {
app: './src/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name][chunkhash].js',
publicPath: '/'
},
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
},
module: {
rules: [
{
test: /\.js$/,
loaders: ['babel-loader'],
exclude: /node_modules/
}
]
}
}
ติดตั้ง css-loader & transformers style พิมพ์คำสั่ง npm install css-loader style-loader --save-dev
สร้าง rule ใน webpack.config.js ประมาณนี้
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
ติดตั้ง babel-loader & babel-core พิมพ์คำสั่ง npm install --save-dev babel-loader babel-core
ลิงค์อ้างอิง Babel
เพิ่ม rules { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
ติดตั้ง babel-cli & babel-preset-es2015 พิมพ์คำสั่ง npm install --save-dev babel-cli babel-preset-es2015 babel-preset-stage-2
สร้างไฟล์ .bablerc แล้วกำหนดค่าดังนี้ { "presets": ["es2015", "stage-2"] }
สร้าง plugins ใน webpack.config.js plugins: []
เพิ่มเงื่อนไขการ minifile เฉพาะ production ที่ webpack.config.js
module.exports = {
...
plugins: []
}
if (process.env.NODE_EN === 'production') {
module.exports.plugins.push(
new webpack.optimize.UglifyJsPlugin()
)
}
เพิ่ม scripts production ที่ package.json "prod": "NODE_ENV=production webpack"
แก้ไข scripts ใหม่ดังนี้
"scripts": {
"dev": "webpack --watch",
"prod": "NODE_ENV=production webpack"
},
ติดตั้ง sass-load & node-sass พิมพ์คำสั่ง npm install sass-loader node-sass --save-dev
เพิ่ม rules ที่ webpack.config.js
{
test: /\.s[ac]ss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
}
ติดตั้ง extract พิมพ์คำสั่ง npm install --save-dev extract-text-webpack-plugin
ลิงค์อ้างอิง extract-text-webpack-plugin
ลิงค์อ้างอิง webpack loaderoptions plugin
แก้ไข rules ที่ webpack.config.js ดังนี้
module: {
rules: [
...
{
test: /\.s[ac]ss$/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'sass-loader'],
fallback: 'style-loader'
})
}
]
},
plugins: [
...
new webpack.LoaderOptionsPlugin({
minimize: inProduction
})
]
/*หมายเหตุ*/ ค่า inProduction มาจาก var inProduction = (process.env.NODE_ENV === 'prod')
ติดตั้ง raw-loader & file-loader พิพม์คำสั่ง npm install --save-dev raw-loader file-loader
เพิ่ม rule
{
test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'file-loader',
options: {
name: 'img/[name].[hash:7].[ext]'
}
}
ติดตั้ง npm i -D purifycss-webpack purify-css
เพิ่ม plugin
--- require
const glob = require('glob');
const PurifyCSSPlugin = require('purifycss-webpack');
--- plugin
new PurifyCSSPlugin({
paths: glob.sync(path.join(__dirname, 'index.html')),
minimize: inProduction
})
npm i jquery clean-webpack-plugin -D
set ค่า webpack.config.js ดังนี้
--- require
const CleanWebpackPlugin = require('clean-webpack-plugin');
--- module
entry: {
main: './src/main.js',
verdor: ['jquery']
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[chunkhash].js'
}
--- plugin
new CleanWebpackPlugin(['dist'], {
_root: __dirname,
verbose: true,
dry: false
})
ติดตั้ง npm install img-loader --save-dev
--- plugin
{
test: /\.(svg|eot|ttf|woff|woff2)$/,
use: 'file-loader'
},
{
test: /\.(png|jpe?g|gif)$/,
loaders: [
{
loader: 'file-loader',
options: {
name: 'img/[name].[hash:7].[ext]'
}
},
'img-loader'
]
}
---
plugins: [
function () {
this.plugin('done', stats => {
require('fs').writeFileSync(
path.join(__dirname, 'dist/manifest.json'),
JSON.stringify(stats.toJson())
)
})
}
]
ติดตั้ง npm i -D html-webpack-plugin
--- require
const HtmlWebpackPlugin = require('html-webpack-plugin')
--- plugin
new HtmlWebpackPlugin({
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
}),
สำหรับ production
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}
}),
]
---
const ExtractTextPlugin = require('extract-text-webpack-plugin')
---
module: {
rules: [
{
loader: ExtractTextPlugin.extract({
loader: 'css-loader'
}),
test: /\.css$/
}
]
}
---
plugins: [
new ExtractTextPlugin('[name].[contenthash].css'),
]
---
const CopyWebpackPlugin = require('copy-webpack-plugin')
---
plugins: [
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, 'static'),
to: 'static',
ignore: ['.*']
}
]),
]
npm install --save-dev image-webpack-loader url-loader
---
module: {
rules: [
{
test: /\.(jpe?g|png|gif|svg)$/,
use: [
{
loader: 'url-loader',
options: { limit: 40000 }
},
'image-webpack-loader'
]
}
]
}
---
entry: {
...
vendor: ['react', 'react-dom', 'react-vue']
},
---
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
}),
]
---
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
...
devtool: 'cheap-module-eval-source-map',
...