Skip to content

yuttasakcom/webpack-manual

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

33 Commits
 
 
 
 

Repository files navigation

Webpack Manual

คู่มือการใช้งาน Webpack ฉบับ YoProgrammer

สารบัญ

Init

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.

Build

webpack src/main.js dist/bundle.js

Watch

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"
},

Config

สร้างไฟล์ 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/
      }
    ]
  }
}

Loader

ติดตั้ง 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

ติดตั้ง 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"] }

Minification

สร้าง 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

ติดตั้ง 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

ติดตั้ง 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')

Relative_URL

ติดตั้ง 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]'
  }
}

Purify_CSS

ติดตั้ง 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
})

Long-Term_Caching

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
})

Optimization_Image

ติดตั้ง 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'
  ]
}

Manifests

---
plugins: [
  function () {
    this.plugin('done', stats => {
      require('fs').writeFileSync(
        path.join(__dirname, 'dist/manifest.json'),
        JSON.stringify(stats.toJson())
      )
    })
  }
]

HTML TEMPLATE

ติดตั้ง 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
  },
}),

WEBPACK DEFINE PLUGIN

สำหรับ production

plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }
  }),
]

Extract Text Plugin

---
const ExtractTextPlugin = require('extract-text-webpack-plugin')

---
module: {
  rules: [
    {
      loader: ExtractTextPlugin.extract({
        loader: 'css-loader'
      }),
      test: /\.css$/
    }
  ]
}

---
plugins: [
  new ExtractTextPlugin('[name].[contenthash].css'),
]

Copy Webpack Plugin

---
const CopyWebpackPlugin = require('copy-webpack-plugin')

---
plugins: [
  new CopyWebpackPlugin([
    {
      from: path.resolve(__dirname, 'static'),
      to: 'static',
      ignore: ['.*']
    }
  ]),
]

Image Webpack Loader

  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'
      ]
    }
  ]
}

Vendor Splitting

---
entry: {
  ...
  vendor: ['react', 'react-dom', 'react-vue'] 
},

---
plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    names: ['vendor', 'manifest']
  }),
]

Provide Plugin

---
plugins: [
  new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
  })
]

Source Map

...
devtool: 'cheap-module-eval-source-map',
...

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published