webpack入口、出口、模式、loader、外掛

weixin_34087301發表於2018-07-14

webpack 基礎知識核心概念:

  • 入口(entry)
  • 輸出(output)
  • loader
  • 外掛(plugins)

練習的程式碼都在這裡
https://github.com/dai1254473705/webpack-test

練習的專案結構:

7450593-cd95ca1d908a2bb8.png
image.png

注意:

  1. 先要全域性安裝webpack,專案中需要開發環境安裝webpack-cli
    如下為專案的配置檔案(master分支):
{
  "dependencies": {},
  "devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "webpack-cli": "^3.0.8",
    "webpack": "^4.16.0"
  }
}
  1. webpack配置檔案的名字一定是webpack.config.js

1. 入口

一個入口起點(或多個入口起點)

module.exports = {
  entry:entry: path.resolve(__dirname, "src/index.js")
};

2.出口

通過 output.filename 和 output.path 屬性,來告訴 webpack bundle 的名稱,以及我們想要 bundle 生成(emit)到哪裡。
如下配置,則在當前專案的dist檔案中生成一個myfirst-webpack.bundle.js,如下所示:

7450593-0080a9a5a51b3cd4.png
image.png

const path = require('path');

module.exports = {
  output: {
  path: path.resolve(__dirname, "dist"),
  filename: "myfirst-webpack.bundle.js"
  }
};

3.loader

webpack 自身只能識別js檔案,但是開發中會有css,圖片等靜態檔案,webpack雖然自身不能識別,但是可以通過loader來處理;實現css、圖片等檔案的打包;

  • loader 要寫在module.rules中:
const path = require('path');

module.exports  = {
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
    ]
  }
};

4.外掛(plugins)

loader 被用於轉換某些型別的模組,而外掛則可以用於執行範圍更廣的任務。外掛的範圍包括,從打包優化和壓縮,一直到重新定義環境中的變數。外掛介面功能極其強大,可以用來處理各種各樣的任務。

const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通過 npm 安裝
const webpack = require('webpack'); // 用於訪問內建外掛

module.exports  = {
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

5. ## 模式

通過選擇 development 或 production 之中的一個,來設定 mode 引數,你可以啟用相應模式下的 webpack 內建的優化

module.exports = {
  mode: 'production'
};

當前全部配置如下:

/**
 * webpack config
 */
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通過 npm 安裝


const config = {
    mode: 'development',
    entry: path.resolve(__dirname, "src/index.js"),
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "myfirst-webpack.bundle.js"
    },
    module:{
        rules:[
            {test:/\.txt$/,use:"raw-loader"},
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({template: './views/index.html'})
    ]
};
module.exports  = config;

練習的時候只需要在專案根目錄開啟終端,輸入webpack就可以編譯;
完整程式碼(master分支為最基礎的配置):https://github.com/dai1254473705/webpack-test

僅適用於學習

相關文章