如何使用webpack5+TypeScript+npm發(fā)布組件庫
一、前言
作為一只前端攻城獅,沒有一個屬于自己的組件庫,那豈不是獅子沒有了牙齒,士兵沒有了武器,姑娘沒有了大寶SOD蜜,你沒有了我....
言歸正傳,下面將給大家介紹如何通過webpack5編譯一個TS組件發(fā)布到NPM平臺。
二、思路
1、通過webpack5初始化一個typescript環(huán)境
2、使用typescript編寫一個組件庫
3、通過webpack5進行編譯
4、配置package.json,通過npm發(fā)布編譯后的組件庫
5、在項目中的引用
三、實現(xiàn)
1、webpack5初始化環(huán)境
【1】創(chuàng)建一個名為simple-js的項目
npm init
【2】安裝webpack相關(guān)的包
npm install webpack webpack-cli --save-dev
【3】使用webpack進行配置
npm webpack-cli init 或 .\node_modules\.bin\webpack-cli init
- 是否使用webpack-dev-server(進行測試)
- 是否創(chuàng)建html 在倉庫里(htmlWebpackPlugin會把打包好的js文件,自動綁到html 文件)
- 是否需要pwa
自動生成文件:
- tsconfig (ts配置文件)
- postcss.config
- webpack.config (webpack配置文件)
【4】配置文件詳情
1、tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/",// 打包到的目錄
"sourceMap": false,// 是否生成sourceMap(用于瀏覽器調(diào)試)
"noImplicitAny": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"declaration": true,// 是否生成聲明文件(重要配置,便于查看方法類型)
"declarationDir": "./dist/types/",// 聲明文件打包的位置
"declarationMap": false,// 是否生成聲明文件map文件(便于調(diào)試)
"moduleResolution": "node",
"module": "esnext",
"target": "es5",// 轉(zhuǎn)化成的目標(biāo)語言
"baseUrl": "./",
"types": [
"node"
],
"typeRoots": [
"./node_modules/@types"
],
"lib": [
"dom",
"es2015"
],
"jsx": "react",
"allowJs": false
},
"include": [
"src/**/*.ts",
"typings.d.ts",
"src/main.js",
],// 要打包的文件
"exclude": [
"node_modules",
"*.test.ts"
]
}2、webpack.config.js
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const path = require('path');
//clean-webpack-plugin: 實現(xiàn)每次編譯時先清理上次編譯結(jié)果
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isProduction = process.env.NODE_ENV == 'production';
const config = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js', // 輸出文件名
library: 'SimpleJS', // 庫的名稱 -全局引入時可以使用
libraryTarget: 'umd', // 支持的模塊系統(tǒng)
// umdNamedDefine: true // 會為 UMD 模塊創(chuàng)建一個命名的 AMD 模塊
},
devServer: {
open: true,
host: 'localhost',
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
}),
new CleanWebpackPlugin()
],
module: {
rules: [
{
test: /\.ts$/i,
loader: 'ts-loader',
exclude: ['/node_modules/'],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: 'asset',
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.jsx', '.js', '...'],
},
};
module.exports = () => {
if (isProduction) {
config.mode = 'production';
} else {
config.mode = 'development';
}
return config;
};2、使用typescript編寫一個組件庫(simple-js)
simple-js組件庫中集成算法、類型判斷等常用的公共方法。
【1】方法文件
src\algorithm\index.ts
import { StorageCapacityUnit } from './algorithm-types';
// @params - str: 文本
// @params - showTotal: 顯示文本的總個數(shù)
// 功能描述:截斷文本,中間出現(xiàn)省略號
const truncateText = (str: string, showTotal: number): string => {
if (str.length > showTotal) {
const prefixNum = Math.floor(showTotal / 2);
const suffixNum = showTotal - prefixNum;
return `${str.slice(0, prefixNum)}...${str.slice(-suffixNum)}`;
}
return str;
}
// @params1 - value: 需要轉(zhuǎn)換的值
// @params2 - sourceUnit: 轉(zhuǎn)換前單位
// @params3 - sourceUnit: 轉(zhuǎn)換后單位
// @params4 - base: 轉(zhuǎn)換進制
// 功能描述:存儲單位的轉(zhuǎn)換,
const unitSwitchForStorageCapacity = (value: number, sourceUnit: StorageCapacityUnit, targetUnit: StorageCapacityUnit, base = 1024): number => {
const unitList = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const sourceUnitIndex = unitList.findIndex(ele => ele === sourceUnit);
const targetUnitIndex = unitList.findIndex(ele => ele === targetUnit);
if (sourceUnitIndex === -1 || targetUnitIndex === -1) {
console.error('轉(zhuǎn)換失敗,sourceUnit或者targetUnit不再轉(zhuǎn)換列表')
return value;
}
const exponent = sourceUnitIndex - targetUnitIndex;
const resValue = value * Math.pow(base, exponent);
return Number.isInteger(resValue) ? resValue : Number(resValue.toFixed(2));
}【2】接口文件
src\algorithm\algorithm-types.ts
export type StorageCapacityUnit = 'B'| 'KB'| 'MB'| 'GB'| 'TB'| 'PB'| 'EB'| 'ZB' | 'YB';
【3】主文件
主文件中是simple-js的導(dǎo)出模塊的入口:
import { truncateText, unitSwitchForStorageCapacity } from './algorithm/index';
import { isObject, isEmptyObject, isNullOrUndefined } from './type/index';
export {
truncateText,
unitSwitchForStorageCapacity,
isObject,
isEmptyObject,
isNullOrUndefined
} 3、通過webpack5進行編譯
編譯:
npm run build
編譯后文件目錄:
main.js:組件庫的主代碼文件
index.d.ts:組件庫的類型文件入口

4、配置package.json,通過npm發(fā)布編譯后的組件庫
{
"name": "simple-js-zyk", //npm平臺的包
"version": "1.0.0",
"description": "工具包",//包的描述說明
"main": "./dist/main.js", // 組件庫的入口文件
"types": "./dist/types/index.d.ts", // 組件庫中類型的文件入口
"files": [
"dist"
], //npm發(fā)布的目錄
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --mode=production --node-env=production",
"build:dev": "webpack --mode=development",
"build:prod": "webpack --mode=production --node-env=production",
"watch": "webpack --watch",
"serve": "webpack serve"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@webpack-cli/generators": "^3.0.7",
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.6.0",
"simple-js-zyk": "^1.0.0",
"ts-loader": "^9.5.1",
"typescript": "^5.4.5",
"webpack": "^5.91.0",
"webpack-cli": "^5.1.4"
}
}npm發(fā)布流程見:npm發(fā)布Vue組件
5、在項目中的引用
【1】在普通js項目中的使用
1)安裝simple-js-zyk包
npm install --save-dev simple-js-zyk
2)項目中在index.html引入
script type="text/javascript" src="./node_modules/simple-js-zyk/dist/main.js"></script>
3)使用
<script type="module">
console.log(SimpleJS.truncateText('xxxxxxxssssss', 4));
console.log(SimpleJS.unitSwitchForStorageCapacity(100, 'MB', 'KB'))
</script>【2】在vue項目中使用
1)安裝simple-js-zyk包
npm install --save-dev simple-js-zyk
2)vue項目tsconfig.json文件中引入simple-js-zyk的文件類型
{
...
"compilerOptions": {
"types": ["node_modules/base-tool-zyk/dist/types"]
}
...
}3)在vue模塊文件中使用
import * as SimpleJS from 'simple-js-zyk';
console.log(SimpleJS.algorithm.truncateText('asxasxsaasss', 3))結(jié)果:

到此這篇關(guān)于使用webpack5+TypeScript+npm發(fā)布組件庫的文章就介紹到這了,更多相關(guān)webpack5發(fā)布組件庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript中window.open在原來的窗口中打開新的窗口(不同名)
本文給大家介紹使用window.open在原來的窗口中打開新的窗口,涉及到win.open新窗口相關(guān)知識,對本文感興趣的朋友參考下2015-11-11
jquery $(document).ready()和window.onload的區(qū)別淺析
這篇文章主要介紹了jquery $(document).ready()和 window.onload的區(qū)別淺析,本文總結(jié)了執(zhí)行時間、編寫個數(shù)不同、簡化寫法等不同的地方,需要的朋友可以參考下2015-02-02
JavaScript中的this例題實戰(zhàn)總結(jié)詳析
使用JavaScript開發(fā)的時候,很多人多多少少都會被this的指向問題搞蒙圈,下面這篇文章主要給大家介紹了關(guān)于JavaScript中this例題實戰(zhàn)的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-06-06
js使用Array.prototype.sort()對數(shù)組對象排序的方法
這篇文章主要介紹了js使用Array.prototype.sort()對數(shù)組對象排序的方法,實例分析了Array.prototype.sort()的原理與相關(guān)的使用技巧,需要的朋友可以參考下2015-01-01

