欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何使用webpack5+TypeScript+npm發(fā)布組件庫(kù)

 更新時(shí)間:2024年04月19日 10:03:52   作者:zyk_520  
這篇文章主要介紹了如何使用webpack5+TypeScript+npm發(fā)布組件庫(kù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧

一、前言

作為一只前端攻城獅,沒(méi)有一個(gè)屬于自己的組件庫(kù),那豈不是獅子沒(méi)有了牙齒,士兵沒(méi)有了武器,姑娘沒(méi)有了大寶SOD蜜,你沒(méi)有了我....

言歸正傳,下面將給大家介紹如何通過(guò)webpack5編譯一個(gè)TS組件發(fā)布到NPM平臺(tái)。

二、思路

1、通過(guò)webpack5初始化一個(gè)typescript環(huán)境

2、使用typescript編寫一個(gè)組件庫(kù)

3、通過(guò)webpack5進(jìn)行編譯

4、配置package.json,通過(guò)npm發(fā)布編譯后的組件庫(kù)

5、在項(xiàng)目中的引用

三、實(shí)現(xiàn)

1、webpack5初始化環(huán)境

【1】創(chuàng)建一個(gè)名為simple-js的項(xiàng)目

npm init

【2】安裝webpack相關(guān)的包

npm install webpack webpack-cli --save-dev

【3】使用webpack進(jìn)行配置

npm webpack-cli init
或
.\node_modules\.bin\webpack-cli init
  • 是否使用webpack-dev-server(進(jìn)行測(cè)試)
  • 是否創(chuàng)建html 在倉(cāng)庫(kù)里(htmlWebpackPlugin會(huì)把打包好的js文件,自動(dòng)綁到html 文件)
  • 是否需要pwa

自動(dòng)生成文件:

  • 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)語(yǔ)言
    "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: 實(shí)現(xiàn)每次編譯時(shí)先清理上次編譯結(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', // 庫(kù)的名稱 -全局引入時(shí)可以使用
        libraryTarget: 'umd', // 支持的模塊系統(tǒng)
        // umdNamedDefine: true // 會(huì)為 UMD 模塊創(chuàng)建一個(gè)命名的 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編寫一個(gè)組件庫(kù)(simple-js)

simple-js組件庫(kù)中集成算法、類型判斷等常用的公共方法。

【1】方法文件

src\algorithm\index.ts

import { StorageCapacityUnit } from './algorithm-types';
// @params - str: 文本
// @params - showTotal: 顯示文本的總個(gè)數(shù)
// 功能描述:截?cái)辔谋?,中間出現(xiàn)省略號(hào)
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)換進(jìn)制
// 功能描述:存儲(chǔ)單位的轉(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、通過(guò)webpack5進(jìn)行編譯

編譯:

npm run build

編譯后文件目錄:

main.js:組件庫(kù)的主代碼文件

index.d.ts:組件庫(kù)的類型文件入口

4、配置package.json,通過(guò)npm發(fā)布編譯后的組件庫(kù)

{
  "name": "simple-js-zyk", //npm平臺(tái)的包
  "version": "1.0.0",
  "description": "工具包",//包的描述說(shuō)明
  "main": "./dist/main.js", // 組件庫(kù)的入口文件
  "types": "./dist/types/index.d.ts", // 組件庫(kù)中類型的文件入口
  "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、在項(xiàng)目中的引用

【1】在普通js項(xiàng)目中的使用

1)安裝simple-js-zyk包

npm install --save-dev simple-js-zyk

2)項(xiàng)目中在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項(xiàng)目中使用

1)安裝simple-js-zyk包

npm install --save-dev simple-js-zyk

2)vue項(xiàng)目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ā)布組件庫(kù)的文章就介紹到這了,更多相關(guān)webpack5發(fā)布組件庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論