【问题标题】:Can't import TypeScript library bundled with WebPack无法导入与 WebPack 捆绑的 TypeScript 库
【发布时间】:2020-11-10 03:05:10
【问题描述】:

在一个 TypeScript 项目中,我尝试导入一个名为“fsaa-util”的 TypeScript 库,该库与 WebPack 捆绑在一起。代码编译得很好,但在运行时尝试使用该库中的对象时,它们是未定义的。

index.ts:

import { MyClass } from "fsaa-util";

let t = new MyClass(); //Throws MyClass is not a constructor.
console.log(t);

库的index.ts:

import "reflect-metadata";

export { default as MyClass } from "MyClass";

MyClass.ts:

export default class MyClass {

}

库的tsconfig.json:

{
    "compilerOptions": {
        "noImplicitAny": true,
        "module": "es6",
        "target": "es6",
        "jsx": "react",
        "jsxFactory": "h",
        "strict": true,
        "experimentalDecorators": true,
        "moduleResolution": "node",
        "declaration": true,
        "declarationDir": "./dist",
        "baseUrl": "./src",
        "outDir": "./dist",
        "plugins": [
            { "transform": "typescript-transform-paths" },
            { "transform": "typescript-transform-paths", "afterDeclarations": true }
        ]
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "dist"
    ]
}

库的Webpack.config.js:

const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
    entry: './src/index.ts',
    output: {
        filename: 'index.js',
        publicPath: '/dist/',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                options: {
                    allowTsInNodeModules: true,
                    appendTsSuffixTo: [/\.vue$/],
                    compiler: 'ttypescript'
                }
            }
        ]
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.vue', '.wasm', '.mjs', '.js', '.json', 'css'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
        },
        modules: ["src", "node_modules"]
    },
    plugins: [
        new VueLoaderPlugin(),
    ]
};

【问题讨论】:

  • “export { default as MyClass }”不是命名导出吗?
  • 向该类添加构造函数。
  • 我已经尝试过并且不会改变任何东西。不需要构造函数,类具有默认构造函数集。
  • 我相信这更像是一个 WebPack 模块解析问题

标签: typescript webpack webpack-3


【解决方案1】:

必须在库的webpack.config.js 的“输出”部分添加这些行:

library: "fsaa-util",
libraryTarget: 'umd',
umdNamedDefine: true

【讨论】:

    猜你喜欢
    • 2019-07-16
    • 2019-09-10
    • 2018-08-23
    • 2016-07-05
    • 2017-10-15
    • 1970-01-01
    • 2017-03-14
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多