我使用Typescript创建了自己的函数库。该库的组件之一是 Aircraft.ts ,它可以导出功能:
export function SimulateAircraft(dt: number, s0: IAircraftState, phi_cmd: number): IAircraftState
然后使用Webpack,ts-loader和dts-bundle将这些文件打包为单个.js文件和单个.d.ts文件。 index.ts 只需重新导出所有组件:
export * from './components/Aircraft'
该库尚未部署到npm,但是我已经使用npm link
在本地开发环境中使用了该库。
然后我将函数从库中导入另一个Typescript项目。
import { IAircraftState, SimulateAircraft } from 'oset';
我在其中使用的功能如下:
setInterval(() => {
const ac = SimulateAircraft(0.1, this.state.ac, 0);
this.setState({ ac });
}, 100);
该项目的构建没有任何错误。 VSCode也不显示任何错误,并且intellisense正确显示了导入的函数定义。 但是在运行时,在浏览器控制台中出现以下错误:
Uncaught TypeError: Object(...) is not a function
错误所指向的对象是SimulateAircraft
,它似乎未定义。我已经搜索了很长时间才能尝试找到解决方案。我发现了类似的错误及其解决方案,但尚未找到能够解决我的问题的解决方案。我非常感谢您的帮助。
webpack.config.js
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const path = require('path');
const libraryName = 'oset';
module.exports = {
mode: "development",
devtool: 'inline-source-map',
entry: './src/index.ts',
output: {
filename: 'oset.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
optimization: {
minimizer: [
new UglifyJsPlugin({
sourceMap: true
})
]
},
module: {
rules: [{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: [/node_modules/, /coverage/]
}]
},
plugins: [
new DtsBundlePlugin()
]
};
function DtsBundlePlugin() { }
DtsBundlePlugin.prototype.apply = function (compiler) {
compiler.plugin('done', function () {
var dts = require('dts-bundle');
dts.bundle({
name: 'oset',
main: 'dist/index.d.ts',
out: 'oset.d.ts',
removeSource: true,
outputAsModuleFolder: true // to use npm in-package typings
});
});
};
package.json
{
"name": "oset",
"version": "0.0.0",
"description": "...",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"build": "webpack",
"clean": "rm -rf dist",
"coverage": "npm test -- --coverage",
"test": "jest --watch"
},
"repository": {
"type": "git",
"url": "..."
},
"devDependencies": {
"@types/jest": "^23.3.1",
"dts-bundle": "^0.7.3",
"jest": "^23.5.0",
"ts-jest": "^23.1.4",
"typescript": "^3.0.3"
},
"dependencies": {
"redux": "^4.0.0"
},
"jest": {
"testEnvironment": "node",
"collectCoverageFrom": [
"<rootDir>/src/*/**.{ts,tsx}"
],
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"verbose": true,
"testURL": "http://localhost/"
}
}
答案 0 :(得分:1)
可能为时已晚,但请尝试:
import * as aircraft from 'oset';
然后:
setInterval(() => {
const ac = aircraft.SimulateAircraft(0.1, this.state.ac, 0);
this.setState({ ac });
}, 100);