前端基建-函数工具库(1)

982 阅读1分钟

创建项目

npm init -y
// 安装ts相关依赖
npm install typescript -D
npm install ts-jest  -D
npm install @types/jest -D

配置 tsconfig.json

{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "declaration": true,// 是否生成`.d.ts`的类型声明文件
    "moduleResolution": "node",
    "outDir": "./dist" /* Redirect output structure to the directory. */,
    "strict": true /* Enable all strict type-checking options. */,
    "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "lib": [],      
    }
}

注意 "declaration": true, 不配置就没法生成类型 配置前 image.png 配置后 image.png

配置webpack.config.js

//安装 
// ts-loader 处理ts,转为webpack能处理的语言
npm install  ts-loader -D 
npm install webpack -D
npm install webpack-cli -D

webpack.config.js

const path = require("path")
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
  mode: "production",
  entry: "./src/index.ts",
  output: {
    filename: "index.js",
    path: path.resolve(__dirname, "dist"),
    // library: 'zt-common-utils',
    library: {
      name: "zy-utils",
      type: "umd", // 打包生成库可以通过esm/commonjs/reqirejs的语法引入
    },
    
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx"],
  },
  module: {
    rules: [
        {
          test: /\.ts$/,
          use: 'ts-loader',
          exclude: /node_modules/,
        },
      ],
  },
  plugins: [
    new CleanWebpackPlugin(), // 添加插件
  ],
}

配置package.json

{
  "name": "zy-utils",
  "version": "1.0.0",
  "description": "## 初始化",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/jest": "^29.5.14",
    "ts-jest": "^29.2.5",
    "ts-loader": "^9.5.1",
    "typescript": "^5.7.2",
    "webpack": "^5.97.1",
    "webpack-cli": "^6.0.1"
  },
  "dependencies": {
    "clean-webpack-plugin": "^4.0.0",
    "path": "^0.12.7"
  }
}

编写工具函数

src/sum.ts

/**
 *
 * @param a 数值1
 * @param b 数值2
 * @returns
 */
const sum = (a: number, b: number): number => {
  // console.log(a);
  return a + b
}
export { sum }

src/index.ts

export { sum } from "./sum"

打包

执行npm run build 生成文件

image.png

本地测试

工具库目录下执行

npm link

测试项目中执行

npm link zy-utils

测试项目中测试

import { sum } from 'zy-utils';

console.log(sum(2, 3)); // 输出: 5

可以看到如下报错

image.png

报错原因:模块使用了 CommonJS/UMD 格式导出,而不是原生的 exportimport。当你尝试按 ESM 格式导入时,Vite 报错说模块中不存在 sum

修改webpack

const path = require("path")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")

module.exports = (env) => {
  const format = env && env.format
  const isESM = env.format === "esm"; // 根据环境变量判断格式
  return {
    mode: "production",
    entry: "./src/index.ts",
    output: {
      filename: format === "esm" ? "index.esm.js" : "index.umd.js",
      path: path.resolve(__dirname, "dist"),
      library:
        format === "esm"
          ? { type: "module" }
          : { name: "zy-utils", type: "umd" }, // 根据格式动态设置 library
    },
    experiments: {
      outputModule: isESM, // 如果是 ESM 格式,则启用 outputModule
    },
    resolve: {
      extensions: [".ts", ".tsx", ".js", ".jsx"],
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          use: "ts-loader",
          exclude: /node_modules/,
        },
      ],
    },
    plugins: [
    ],
  }
}

修改package.json

{
  "name": "zy-utils",
  "version": "1.0.0",
  "description": "## 初始化",
  "main": "dist/index.umd.js",
  "exports":{
    "./package.json": "./package.json",
    ".": {
      "import": "./dist/index.esm.js",  
      "require": "./dist/index.umd.js" 
    }
  },
  "types": "dist/index.d.ts",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build:esm": "webpack --config webpack.config.js --env format=esm",
    "build:umd": "webpack --config webpack.config.js --env format=umd",
    "build": "rm -rf dist && npm run build:esm && npm run build:umd"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/jest": "^29.5.14",
    "ts-jest": "^29.2.5",
    "ts-loader": "^9.5.1",
    "typescript": "^5.7.2",
    "webpack": "^5.97.1",
    "webpack-cli": "^6.0.1"
  },
  "dependencies": {
    "clean-webpack-plugin": "^4.0.0",
    "path": "^0.12.7"
  }
}

重新build后,测试成功。

下一期,添加单元测试。