WEBPACK_IMPORTED_MODULE_13___default(...) 不是函数

Hug*_*ace 5 javascript typescript webpack

上下文:我正在使用 TypeScript 和 Webpack 构建一个小型库(这里我们称之为 myLibrary)。我构建了它,将它导入到反应应用程序中,但反应应用程序崩溃了。

图书馆一侧

我的主要入口点 (index.ts) 有一个默认导出:

import wrapper from "./wrapper";

export default wrapper;
Run Code Online (Sandbox Code Playgroud)

我的包装文件公开了一个默认导出,它是一个函数 (wrapper.ts):

const create = () => {
  // Some functions
  return {
    init,
    close,
    getBase,
    setBase
  }
}
export default create;
Run Code Online (Sandbox Code Playgroud)

该库轻松通过所有单元测试。

反应应用端

在 React 应用程序中构建和导入我的库后,我没有 Typescript 错误,但我的 React 应用程序崩溃并显示以下消息:

TypeError: myLibrary__WEBPACK_IMPORTED_MODULE_13___default(...) is not a function
Run Code Online (Sandbox Code Playgroud)

在这样调用我的库之后:

import createAPI from "myLibrary";
const api = createAPI(); // Crash here even though I should have a nice object containing my functions
Run Code Online (Sandbox Code Playgroud)

这真的很奇怪,因为 TS 真的很好地编译为 JS,没有任何警告。

我使用命令构建的库 wepback 配置(4.43.0)webpack --config webpack.config.js

const path = require('path');

module.exports = {
  mode: "production",
  entry: "./src/index.ts",
  output: {
    filename: "index.js",
    path: path.resolve(__dirname, 'dist'),
  },
  resolve: {
    extensions: [".ts", ".js"]
  },
  module: {
    rules: [
      { test: /\.tsx?$/, loader: "ts-loader" }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我的库 TS 配置(3.7.3):

{
  "compilerOptions": {
    "outDir": "dist",
    "target": "es5",
    "module": "CommonJS",
    "lib": ["dom", "dom.iterable", "esnext"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "preserve",
    "declaration": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true
  },
  "include": ["src"]
}

Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激 :)

编辑:将默认导出更新为命名导出后:

import { createAPI } from "myLibrary";
const api = createAPI();
Run Code Online (Sandbox Code Playgroud)

我有一个新的错误

TypeError: Object(...) is not a function
Run Code Online (Sandbox Code Playgroud)

当我尝试时,console.log(typeof createAPI);我得到了一个未定义的,这应该是不可能的,因为我的测试正在通过并且 TS 没有抱怨。

tmh*_*005 2

In your webpack config of the library to point out library name & its module type:

output: {
  path: './dist',
  filename: 'index.js',
  library: 'scorm-wrapper',
  libraryTarget: 'umd'
},
Run Code Online (Sandbox Code Playgroud)