javascript - WEBPACK_IMPORTED_MODULE_13___default(...) 不是函数

标签 javascript typescript webpack

上下文:我正在使用 TypeScript 和 Webpack 构建一个小型库(在这里我们称之为 myLibrary)。我构建了它,将它导入到 react 应用程序中,但 react 应用程序崩溃了。
图书馆侧
我的主要入口点(index.ts)有一个默认导出,如下所示:

import wrapper from "./wrapper";

export default wrapper;
我的包装文件公开了一个默认导出,它是一个函数 (wrapper.ts):
const create = () => {
  // Some functions
  return {
    init,
    close,
    getBase,
    setBase
  }
}
export default create;
该库轻松通过所有单元测试。
React 应用端
在 React 应用程序中构建并导入我的库后,我没有 Typescript 错误,但我的 React 应用程序崩溃并显示以下消息:
TypeError: myLibrary__WEBPACK_IMPORTED_MODULE_13___default(...) is not a function
像这样调用我的图书馆后:
import createAPI from "myLibrary";
const api = createAPI(); // Crash here even though I should have a nice object containing my functions
这真的很奇怪,因为 TS 真的很好地编译为 JS 而没有任何警告。
我使用命令 webpack --config webpack.config.js 构建的库 wepback 配置 (4.43.0) :
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" }
    ]
  }
}
我的库 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"]
}

任何帮助将不胜感激 :)
编辑 :
将默认导出更新为命名导出后:
import { createAPI } from "myLibrary";
const api = createAPI();
我有一个新错误
TypeError: Object(...) is not a function
当我尝试 console.log(typeof createAPI);我得到了一个未定义的,这应该是不可能的,因为我的测试正在通过并且 TS 没有提示。

最佳答案

在库的 webpack 配置中指出库名称及其模块类型:

output: {
  path: './dist',
  filename: 'index.js',
  library: 'scorm-wrapper',
  libraryTarget: 'umd'
},

关于javascript - WEBPACK_IMPORTED_MODULE_13___default(...) 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63135245/

相关文章:

javascript - Coffeescript 在函数中包装文件

typescript - 如何在带有 TypeScript 的 redux 应用程序中使用选择器?

angular - 如何在 Angular 8 项目中为 angular CLI 配置自定义 webpack?

javascript - 优化 jQuery 选择器的最佳方式,为什么?

javascript - 脚本438 : Object doesn't support property or method 'indexOf'

TypeScript - 如何排除其中一种类型?

javascript - Laravel Uncaught ReferenceError webpackJsonp is not defined at app.js :1

webpack - 无法在 Chrome 源选项卡中加载 webpack 源文件的内容

php - IDE 能够保存到两个位置和一个 SVN 存储库吗?

html - 播放字节数组缓冲区中的音频?