typescript 为多个项目中的泛型功能创建类型脚本库

eagi6jfj  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(105)

我想导出几个类,有些是独立的,有些是相互需要的,用一个名称空间 Package ,作为一个模块供其他项目使用。
所以我设置了一个Webpack构建,将它们编译成一个缩小的.js文件和一个.d.ts文件,它们都由名称空间“Platform” Package 。
下面是我用于自定义事件的示例类:

namespace Platform {
    export class GameEvent {
        ****code****
    }
}

问题是,一旦我将它们 Package 在这个名称空间中,构建就会失败,并显示以下错误:
./Utilities/GameEvent中的错误.ts模块构建失败(来自../node_modules/ts-loader/index.js):错误:类型脚本在对象加载程序(\平台\节点模块\ts加载程序\dist\index.js:23:5)的成功加载程序(\平台\节点模块\ts加载程序\dist\index. js:40:5)的makeSourceMapAndFinish(\平台\节点模块\ts加载程序\dist\index.js:53:18)处未发出\平台\src\实用程序\游戏事件. ts的输出
下面是我tsconfig:

{
    "compilerOptions": {
        "target": "es6",
        "module": "esnext",
        "strict": true,
        "noEmit": false,
        "importHelpers": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "sourceMap": true,
        "baseUrl": "./src",
        "rootDir": "./src",
        "outDir": "./types",
        "emitDeclarationOnly": true,
        "declaration": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "lib": [
            "es6",
            "dom"
        ],
        "removeComments": true,
        "typeRoots": [
            "node_modules/@types",
            "node_module/phaser/types"
        ],
        "types": [
            "phaser",
            "jest"
        ]
    },
    "include": [
        "src/**/*",
    ]
}

下面是我webpack.config.js:

const path = require("path");
const webpack = require('webpack');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const DeclarationBundlerPlugin = require('declaration-bundler');
const fs = require('fs');

const srcDir = path.resolve(__dirname, 'src');
const typesDir = path.resolve(__dirname, 'types');

function scanDirectory(dir) {
  const fileArr = [];

  fs.readdirSync(dir).forEach((file) => {
    const filepath = path.join(dir, file);
    if (fs.lstatSync(filepath).isDirectory()) {
      fileArr.push(...scanDirectory(filepath));
    } else if (/\.tsx?$/.test(file)) {
      fileArr.push(path.resolve(filepath));
    }
  });

  return fileArr;
}

const entryPoints = scanDirectory(srcDir);
const typeEntryPoints = scanDirectory(typesDir);

module.exports = {
  mode: "production",
  context: path.resolve(__dirname, 'src'),
  entry: {
    'platform': entryPoints
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: "[name].min.js",
  },
  externals: {
    phaser: 'phaser',
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: [
          {
            loader: 'ts-loader',
          },
        ],
        include: [path.resolve(__dirname, 'src')],
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.DefinePlugin({
      'typeof SHADER_REQUIRE': JSON.stringify(false),
      'typeof CANVAS_RENDERER': JSON.stringify(true),
      'typeof WEBGL_RENDERER': JSON.stringify(true)
    }),
    new DeclarationBundlerPlugin({
      entry: typeEntryPoints,
      moduleName: 'Platform',
      out: './platform.d.ts',
    }),
  ],
  performance: { hints: false },
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: true,
          safari10: true,
          mangle: true,
          output: {
            comments: false
          }
        }
      })
    ]
  }
};

这些是我的devDependencies:

"@jest/globals": "^29.3.1",
    "@declaration-bundler": "^1.0.1",
    "@types/jest": "^29.2.5",
    "before-build-webpack": "^0.2.13",
    "clean-webpack-plugin": "^3.0.0",
    "glob": "^8.0.3",
    "html-webpack-plugin": "^5.3.1",
    "jest": "^29.3.1",
    "jest-canvas-mock": "^2.4.0",
    "jest-environment-jsdom": "^29.3.1",
    "terser-webpack-plugin": "^5.3.6",
    "ts-jest": "^29.0.3",
    "ts-loader": "^8.0.18",
    "ts-node": "^10.9.1",
    "typescript": "^4.9.4",
    "webpack": "^5.28.0",
    "webpack-cli": "^4.9.1"

我尝试对每个没有名称空间的文件使用“export default class”,但是当我发布包并在另一个项目中使用它时,它无法将其识别为模块,并且无法构建/测试。
我该怎么做呢?

chhkpiq4

chhkpiq41#

好的,我想通了,不是完全按照我想的那样,但效果很好。
下面是我的webpack.config.js:

const path = require("path");
const webpack = require('webpack');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const DtsBundleWebpack = require("dts-bundle-webpack");
const removeEmptyDirectories = require('remove-empty-directories');

const libPath = path.resolve(__dirname, 'lib');

module.exports = {
  mode: "production",
  context: path.resolve(__dirname, 'src'),
  entry: {
    'platform': "./platform.ts"
  },
  output: {
    path: libPath,
    filename: "[name].min.js",
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.DefinePlugin({
      'typeof SHADER_REQUIRE': JSON.stringify(false),
      'typeof CANVAS_RENDERER': JSON.stringify(true),
      'typeof WEBGL_RENDERER': JSON.stringify(true)
    }),
    new DtsBundleWebpack({
      name: "<lib name>",
      main: "lib/platform.d.ts",
      out: "platform.d.ts",
      removeSource: true,
      outputAsModuleFolder: true
    }),
    function () {
      this.hooks.done.tap("Done", (stats) => {
        removeEmptyDirectories(libPath);
      });
    }
  ],
  performance: { hints: false },
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: true,
          safari10: true,
          mangle: true,
          output: {
            comments: false
          }
        }
      })
    ]
  }
};

我的文件结构是这样的:
file structure src/ folder
其中每个index.ts文件都有一个针对每个类文件的“export * from 'filename'"。
并且platform.ts文件导出所有模块

相关问题