Webpack4 配置 Externals

Externals 配置項用來告訴 Webpack 要構建的代碼中使用了哪些不用被打包的模塊,也就是說這些模版是外部環境提供的,Webpack 在打包時可以忽略它們。

1.有些 JavaScript 運行環境可能內置了一些全局變量或者模塊,例如在你的 HTML BODY標籤裏通過以下代碼:

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>

引入 jquery 後,全局變量 jQuery 就會被注入到網頁的 JavaScript 運行環境裏。就可以直接通過window.$來訪問jQuery對象。

2.當運行環境內置了jQuery全局變量(即在body中使用script標籤引入了jquery框架),如果同時又使用模塊化的方式安裝並使用了 jQuery(npm install jquery --save),可能這個時候就會出現重複引用框架的問題。

import $ from 'jQuery';
$('body');

當構建後你會發現輸出的 bundle.js 裏包含的 jQuery 庫的內容,這導致 jQuery 庫出現了2次,第一次是body中的script標籤加載,第二次是 bundle.js 中加載,浪費加載流量,最好是 bundle.js裏不會包含 jQuery 庫的內容。那這個時候就用上 Externals 的配置項了

簡單的使用案例:

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist'),
  },
  externals: {
    // 把導入語句裏的 LJquery 替換成運行環境裏的全局變量 jQuery
    LJquery: 'jQuery'
  },
};

1.模塊化安裝jQuery

1.新建一個項目

|-- index.html
|-- node_modules
|-- package-lock.json
|-- package.json
|-- src
|   |-- common.js
|   `-- main.js
`-- webpack.config.js

package.json

{
  "name": "testdevserver",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server",
    "build": "webpack --mode production"
  },
  "author": "liujun",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.35.3",
    "webpack-cli": "^3.3.6",
    "webpack-dev-server": "^3.7.2"
  },
  "dependencies": {
    "jquery": "^3.4.1"
  }
}

1.安裝HTTP服務器開發工具:

npm install [email protected] --save

npm install [email protected] --save-dev

2.編寫啓動服務器腳本:

"dev": "webpack-dev-server" 或者 "dev": "webpack-dev-server --hot --devtool source-map"

3.編寫項目打包腳本:"build": "webpack --mode production"

webpack.config.js


const path = require('path');

module.exports = {
  entry: './src/main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist'),
  },
  devServer: {
    // 1.指定服務的ip
    host: "localhost",

    // 2.指定服務的端口
    port: 9000,

    // 3.開發環境進行http的代理
    proxy: {
      // 匹配 url 路徑的開頭
      '/api': {
        // 1.路勁只要是/api開頭的url都代理到下面這個網站。
        // 例如:fetch('/api/xxxx') 會代理到 https://news-at.zhihu.com/api/xxxx
        // 例如:fetch('http://localhost:9000/api/xxxx') 這種寫法會代理失敗
        target: 'https://news-at.zhihu.com',
        ws: true, // 2.允許代理 websockets 協議
        changeOrigin: true //3.需要虛擬託管的站點要設計爲true。建議設爲 true,開發時大部分情況都是虛擬託管的站點
      }
    }
  }
};

common.js

// 導入node_modules中的jquery框架
let $ = require('jQuery')
function get(content) {
  // 2.使用jQuery的 ajax 發起網絡請求
  $.ajax({
    url:"/api/4/news/latest",
    success:function(result){
       console.log('result=', result)
    },
    error:function(error){
      console.log('error=', error)
    }
  })
}

main.js

// 1.通過 CommonJS 規範導入 get 函數
const get = require('./common.js');
// 2.執行 get 函數
get();

index.html

<html>
<head>
  <meta charset="UTF-8">
</head>
<body>
<div id="app"></div>
<!--1.導入 Webpack 輸出的 JavaScript 文件-->
<!-- <script src="../dist/main.js"></script> -->

<!--2.導入 DevServer 輸出的 JavaScript 文件-->
<script src="bundle.js"></script>
</body>
</html>

2.啓動本地HTTP服務

打開終端,在項目的根目錄執行:npm run dev 命令, DevServer 就啓動了,這時你會看到控制檯有一串日誌輸出:

PS F:\blog\webpack-study\webpackCode\09-配置-Externals> npm run dev

> testdevserver@1.0.0 dev F:\blog\webpack-study\webpackCode\09-配置-Externals
> webpack-dev-server

i 「wds」: Project is running at http://localhost:9000/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from F:\blog\webpack-study\webpackCode\09-[./src/main.js] 89 bytes {main} [built]
    + 19 hidden modules
    ....
    ....
i 「wdm」: Compiled successfully.

這意味着 DevServer 啓動的 HTTP 服務器監聽在 http://localhost:9000/ ,DevServer 啓動後會一直駐留在後臺保持運行,訪問這個http://localhost:9000/網址你就能獲取項目根目錄下的 index.html。 用瀏覽器打開這個地址你會發現頁面引用的 bundle.js文件自動輸出到了項目的根目錄, 查看網頁上的bundle.js會發現jquery框架也被打包到 bundle.js 文件中了。

3.訪問 http://localhost:9000 , 這時你會看到控制檯有一串日誌輸出:

result= {date: "20190905", stories: Array(3), top_stories: Array(5)}
date: "20190905"
stories: (3) [{}, {}, {}]
top_stories: (5) [{}, {}, {}, {}, {}]
__proto__: Object

2. 運行環境添加全局變量jQuery

index.html

<html>
<head>
  <meta charset="UTF-8">
</head>
<body>
<div id="app"></div>
<!--1.導入 Webpack 輸出的 JavaScript 文件-->
<!-- <script src="../dist/main.js"></script> -->

<!-- 2.導入外部的jquery框架,全局變量 `jQuery` 就會被注入到網頁的 JavaScript 運行環境裏 -->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    
<!--3.導入 DevServer 輸出的 JavaScript 文件-->
<script src="bundle.js"></script>
</body>
</html>

打開終端,在項目的根目錄執行:npm run dev 命令, DevServer 就啓動了,這時你會看到控制檯有一串日誌輸出:

PS F:\blog\webpack-study\webpackCode\09-配置-Externals> npm run dev

> testdevserver@1.0.0 dev F:\blog\webpack-study\webpackCode\09-配置-Externals
> webpack-dev-server

i 「wds」: Project is running at http://localhost:9000/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from F:\blog\webpack-study\webpackCode\09-[./src/main.js] 89 bytes {main} [built]
    + 19 hidden modules
    ....
    ....
i 「wdm」: Compiled successfully.

這個時候運行項目還是正常,但是這個時候會導致 jquery庫出現了2次,第一次是body中的script標籤加載,第二次是 bundle.js 中加載,我們期望最好是 bundle.js裏不會包含 jquery 庫的內容。那這個時候就用用上 Externals 的配置項了

2.配置-Externals

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, './dist'),
  },
    
  // 指定引用的哪些模塊不需要打包到 bundle.js 中  
  externals: {
    // 把導入語句裏的 LJquery 替換成運行環境裏的全局變量 jQuery
    LJquery: 'jQuery'
  },
    
  devServer: {
    host: "localhost",
    port: 9000,
    proxy: {
      '/api': {xx
        target: 'https://news-at.zhihu.com',
        ws: true, 
        changeOrigin: true
      }
    }
  }
};

commont.js

// 1.導入運行環境中全局變量中的 jQuery 對象
let $ = require('LJquery')

// 2.導入node_modules中的jquery框架
// let $ = require('jQuery')

function get(content) {
  // 2.使用jQuery的 ajax 發起網絡請求
  $.ajax({
    url:"/api/4/news/latest",
    success:function(result){
       console.log('result=', result)
    },
    error:function(error){
      console.log('error=', error)
    }
  })
}

// 通過 CommonJS 規範導出 get 函數
module.exports = get;

打開終端,在項目的根目錄執行:npm run dev 命令, DevServer 就啓動了,這時你會看到控制檯有一串日誌輸出:

PS F:\blog\webpack-study\webpackCode\09-配置-Externalsr> npm run dev

> testdevserver@1.0.0 dev F:\blog\webpack-study\webpackCode\09-配置-Externals
> webpack-dev-server

i 「wds」: Project is running at http://localhost:9000/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from F:\blog\webpack-study\webpackCode\09-[./src/main.js] 89 bytes {main} [built]
    + 19 hidden modules
    ....
    ....
i 「wdm」: Compiled successfully.

這個時候運行項目還是正常,注意這個時候到運行的頁面上查看 bundle.js,裏不會包含 jquery 庫的內容。

結論:

當在webpack.config.js中配置`Externals 項時,Externals 項用來告訴 Webpack 構建時在代碼中使用了哪些不用被打包的模塊。這樣可以防止框架的2次引用問題,也可以實現 Webpack 打包的優化,在使用第三方庫時可以直接使用cnd上的資源, 而不用打包到bundle.js中。

源碼下載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章