typescript - 无法导入与 WebPack 捆绑的 TypeScript 库
问题描述
在一个 TypeScript 项目中,我试图导入一个与 WebPack 捆绑在一起的名为“fsaa-util”的 TypeScript 库。代码编译得很好,但在运行时尝试使用该库中的对象时,它们是未定义的。
索引.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(),
]
};
解决方案
必须在库的“输出”部分添加这些行webpack.config.js
:
library: "fsaa-util",
libraryTarget: 'umd',
umdNamedDefine: true
推荐阅读
- axios - 使用 axios keep alive 连接多台服务器
- flutter - 在飞镖颤动中自动将json转换为对象
- java - Spring Boot + OAuth2 + REST API - 找不到证书路径
- javascript - 无法获取当前页面以将活动类添加到 Safari 中的导航项
- python-3.x - 如何使用python在一行中打印特定字符?
- html - 如何并排显示记录
- node.js - 将 NodeJS 部署到 Heroku 时出现路由错误
- kubernetes - GCP K8s 原生入口保留客户端 IP
- android - 工具栏菜单文本对齐
- javascript - 没有类的第一个元素的 CSS 选择器