1. 程式人生 > 實用技巧 >webpack配置庫的學習筆記

webpack配置庫的學習筆記

目錄

webpack程式碼

程式碼很簡單

const path=require('path')

module.exports={
 mode:'production',
 entry:'./src/index.js',
 externals:['lodash'],
 output:{
   path:path.resolve(__dirname,'dist'),
   filename:"library.js",
   library:'library',//配置一個全域性變數叫library
   libraryTarget:'umd'
 }
}

目錄

筆記

初始化

npm init -y
{
  "name": "library-webpack",
  "version": "1.0.0",
  "description": "a webpack file of library",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "zhangmiao",
  "license": "MIT"
}

"license": "MIT"表示完全開源

建立目錄

src/
    + math.js
    + str.js
    + index.js
//math.js
export function add(a,b){
  return a+b;
}

export function minus(a,b){
  return a-b;
}

export function multiply(a,b){
  return a*b;
}

export function division(a,b){
  return a/b;
}

//str.js
export function join(a, b) {
  return a + ' ' + b;
}

//index.js

import * as math from './math'; //將math檔案中的所有方法引出來取名為math
import * as string from './str'; 

export default {math,string} //暴露出去

安裝webpack

npm install webpack webpack-cli --save

package.json

  "scripts": {
    "webpack": "webpack"
  },

執行打包

npm run webpack

庫的引用方法

es6:import library from 'library'
command.js:const library=require('library');
amd:require(['library'],function(){
    
})

方法有很多,想要我們的庫可以被引用,需要這樣配置

output:{
   path:path.resolve(__dirname,'dist'),
   filename:"library.js",
   libraryTarget:'umd'
 }

libraryTarget:'umd' ,表示這個庫被掛在哪裡。umd表示通用的,可以使庫被上面的方法使用。

還有通過script標籤的引入方法,如果要使library可以做一個全域性變數,如下:

<script src="library.js"></script>

library.math//全域性

配置方法

 output:{
   path:path.resolve(__dirname,'dist'),
   filename:"library.js",
   library:'library',//配置一個全域性變數叫library
   libraryTarget:'umd'
 }

需要加一條library:'全域性變數名',表示要給使用庫的環境配置一個全域性變數,打包後得到library檔案,如果我們在一個html檔案中引用這個庫,就可以得到library這個全域性變數

libraryTarget:'umd'指庫掛在什麼地方,我們可以換成libraryTarget:'this',這樣庫就掛在this上。在使用script標籤時,就需要使用this.library了,window同理。但是這樣是不能使用es6,amd方法引用庫的。node環境下就配置為libraryTarget:'global'

自己寫的庫引用其他庫

在str.js中使用Lodash

import _ from 'lodash'

export function join(a, b) {
  // return a + ' ' + b;
  return _.join([a,b],' ')
}

我們進行打包

 Asset      Size  Chunks             Chunk Names
library.js  72.8 KiB       0  [emitted]  main

檔案從之前的1.54kib變成了72.8kib,這是因為我們使用了lodash這個第三方庫。

如果在使用自己的庫的時候,同時還引入了lodash,就有兩份lodash庫了。

import library from 'library'
import lodash from 'lodash'

我們可以這樣配置

 mode:'production',
 entry:'./src/index.js',
 externals:['lodash'],

externals:['lodash'],這個配置是讓webpack打包時,如果發現有Lodash包,就不要打包在我們的程式碼裡面。

這樣在使用library庫時library裡面是沒有lodash的,就需要使用者自己引入一個Lodash了

externals還有其他用法,參考https://www.webpackjs.com/configuration/externals/#externals

入口檔案

我們最終給使用者使用的是dist目錄下的library.js檔案,我們需要再package.json檔案中進行修改。

"main": "./dist/index.js",

npm註冊

https://www.npmjs.com/

申請註冊賬號

在命令列中輸入npm adduser

新增使用者名稱和密碼

執行npm push命令釋出庫,別人直接npm install 就行,當然庫名不能和別的庫名相同。