Webpack 4x 之路 ( 一 )

爲何須要webpack

如今的前端網頁很是豐富,特別是SPA技術流行後,js的複雜度增長而且有時須要一大堆的依賴包,還須要解決 SCSS Lesscss預處理等的編譯工做。因此如今的前端已經至關依賴 webpack 來更好的管理項目了。

如今所流行的vue react angluar 已經和webpack很是的密切了,官方都推出了和自身框架依賴的webpack構架工具。css

什麼是webpack

webpack 能夠看做是一個打包工具,它能夠分析你的項目結構,而後找到js 模塊以及一些瀏覽器不能直接執行的一些語言好比 Less 、TypeScript 等,並將其轉換和打包爲一個合法的格式以供瀏覽器使用。webpack從3.0以後還擔負起了優化項目的功能.

如今的webpack已經到了4.X版本了,我也是全程使用了 webpack ^4.4.1

webpack安裝和使用html

mkdir webpack_demo
cd webpack_demo
// npm初始化
npm init
// 而後一直回車

安裝webpack前端

// 不建議全局安裝
cnpm install webpack --save-dev

// --save是要保存到package.json中,dev是在開發時使用這個包,而生產環境中不使用。

首先來一個小demo吧

目錄結構vue

| dist
    - index.html
| node_modules
| src
    - index.js

完善文件內容node

// index.js
import _ from 'lodash';
function component() {
  var element = document.createElement('div');

  // Lodash(目前經過一個 script 腳本引入)對於執行這一行是必需的
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  return element;
}

document.body.appendChild(component());
// index.html
<!doctype html>
<html>
  <head>
    <title>Getting Started</title>
  </head>
  <body>
    <script src="./bundle.js"></script>
  </body>
</html>
// 執行命令
$ npx webpack src/index.js --output dist/bundle.js

npx: installed 1 in 7.613s
Path must be a string. Received undefined
D:\myweb\webpack\webpack_study_demo\webpack_demo01\node_modules\_webpack@4.4.1@webpack\bin\webpack.js
The CLI moved into a separate package: webpack-cli
Would you like to install webpack-cli? (That will run npm install -D webpack-cli) (yes/NO)NO
It needs to be installed alongside webpack to use the CLI


// 這裏提示安裝 webpack-cli
// 是由於到了webpack4,  webpack 已經將 webpack 命令行相關的內容都遷移到 webpack-cli,因此除了 webpack 外,咱們還須要安裝 webpack-cli:
// 安裝webpack-cli
cnpm install webpack-cli --save
// 在次執行
npx webpack src/index.js --output dist/bundle.js
npx: installed 1 in 5.327s
Path must be a string. Received undefined
D:\myweb\webpack\webpack_study_demo\webpack_demo01\node_modules\_webpack@4.4.1@webpack\bin\webpack.js
Hash: c0cb86e7079d57cac106
Version: webpack 4.4.1
Time: 4707ms
Built at: 2018-4-2 21:18:48
    Asset      Size  Chunks             Chunk Names
bundle.js  69.9 KiB       0  [emitted]  main
Entrypoint main = bundle.js
   [1] (webpack)/buildin/module.js 519 bytes {0} [built]
   [2] (webpack)/buildin/global.js 509 bytes {0} [built]
   [3] ./src/index.js 266 bytes {0} [built]
    + 1 hidden module

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/concepts/mode/

// 有一個警告
// 說'mode'沒有定義,這是 webpack  4x 引入的,有兩個值,development 和 production。默認是production.

因爲webpack 默認的入口文件是從./src/index.js,輸出是./dist/main.js 。所以能夠直接 npx webpack --mode development react

> npx webpack --mode development
npx: installed 1 in 5.759s
Path must be a string. Received undefined
D:\myweb\webpack\webpack_study_demo\webpack_demo01\node_modules\_webpack@4.4.1@webpack\bin\webpack.js
Hash: 36739af911cbe57bdd95
Version: webpack 4.4.1
Time: 1060ms
Built at: 2018-4-2 21:25:02
  Asset     Size  Chunks             Chunk Names
main.js  550 KiB    main  [emitted]  main
Entrypoint main = main.js
[./node_modules/_webpack@4.4.1@webpack/buildin/global.js] (webpack)/buildin/global.js 509 bytes {main} [built]
[./node_modules/_webpack@4.4.1@webpack/buildin/module.js] (webpack)/buildin/module.js 519 bytes {main} [built]
[./src/index.js] 266 bytes {main} [built]
    + 1 hidden module

// 打包完畢了
// 咱們能夠打開 `dist/index.html` 查看一下.

配置文件webpack

上面的 demo 並無使用配置文件,而是使用 CLI 來實現打包的,那麼咱們如今來學習一下配置文件吧。web

// webpack.config.js
module.exports = {
    //入口文件的配置項
    entry:{},
    //出口文件的配置項
    output:{},
    //模塊:例如解讀CSS,圖片如何轉換,壓縮
    module:{},
    //插件,用於生產模版和各項功能
    plugins:[],
    //配置webpack開發服務功能
    devServer:{}
}
入口起點

單文件npm

module.exports = {
    entry: "./src/index.js"
}

多文件json

// 對象語法
module.exports = {
    entry: {
        app: "./sec/app.js",
        vendors: "./src/vendors.js" 
    }
}

// 應用場景: 分離應用程序、和第三方庫入口、多頁面應用程序

// 多頁面應用程序
const config = {
  entry: {
    pageOne: './src/pageOne/index.js',
    pageTwo: './src/pageTwo/index.js',
    pageThree: './src/pageThree/index.js'
  }
};
出口

基本用法

// webpack.config.js
const path = require('path');
const config = {
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

module.exports = config;

多入口起點

//
{
    entry: {
        app: './src/app.js',
        search: './src/search.js'
    },
    output: {
        filename: '[name].js',
        path: __dirname + '/dist'
    }
}
// 這裏的[name]是佔位符,以後會替換爲 app、search
// 寫入到硬盤:./dist/app.js, ./dist/search.js

繼續上面的小demo

// webpack.config.js
var path = require('path')
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  }
}
// 執行
$ npx webpack --config webpack.config.js
// 一樣能打包OK

上面講的比較零碎呢,看着不爽,那咱們再來一個比較實用一點的demo吧

目錄結構
| dist
    - index.html
| src
    - index.js
| package.json
| webpack.config.js
具體代碼實現
// webpack.config.js
var path = require('path')
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/bundle.js'
  }
}
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="title"></div>
  <script src="./js/bundle.js"></script>
</body>
</html>
// index.js
document.getElementById('title').innerHTML = 'hello webpack';

到了重點所在了哦

// package.json
{
  "name": "webpack_new_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode development"
    // "build": "webpack --config webpack.config.js --mode development"
    // 上面兩種配置等價,--config webpack.config.js能夠不寫,默認是它。
    // webpack 4.0以後多了mode的配置,所以咱們須要配置一下,否則會出現警告哦
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.4.1",
    "webpack-cli": "^2.0.13"
  }
}

運行一下

$ npm run build

> webpack_new_test@1.0.0 build D:\myweb\webpack\webpack_study_demo\webpack_new_test
> webpack --mode development

Hash: 8603f6b2e76022d881d9
Version: webpack 4.4.1
Time: 106ms
Built at: 2018-4-3 16:32:55
       Asset      Size  Chunks             Chunk Names
js/bundle.js  2.87 KiB    main  [emitted]  main
Entrypoint main = js/bundle.js
[./src/index.js] 61 bytes {main} [built]
  • 補充
// 按道理咱們在本地安裝了webpack,這部就是應該直接運行webpack 就能夠打包了嘛

>$  webpack
webpack : 沒法將「webpack」項識別爲 cmdlet、函數、腳本文件或可運行程序的名稱。請檢查名稱的拼寫,若是包括路徑,請確保路
徑正確,而後再試一次。
所在位置 行:1 字符: 1
+ webpack
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (webpack:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

// 偏偏報錯了呢


// 解決辦法一
全局安裝 webpack 和 webpack-cli

// 解決辦法二
就是上訴咱們在package.json中進行配置
"build": "webpack --mode development"
未完待續,小編會繼續往下寫哦~~
參考文獻

官方文檔
技術胖

相關文章
相關標籤/搜索