我目前正在尝试开始将 Javascript Webpack 项目转换为在 Typescript 中工作,以便一切都可以很好地输入。然而,我的配置似乎无法识别我已更改为 Typescript 的文件。
项目编译,但我在运行时收到此错误:
TypeError: Angle.cyclic3dAxis is not a function
Angle 是我用 Typescript 重写的(以前的 Javascript)文件,由 2 个小的静态函数组成,格式如下:
export class Angle
{
public static cyclic3dAxis(i: number): number{ /* function defined here */ }
public static anotherFunction(): number{/*defined here*/}
}
原始 Javascript 文件(我没有编写,但可以工作),我将其替换为 TS 文件:
define([],function()
{
var Angle = { };
Angle.cyclic3dAxis = function(i) { /* function defined here */ };
Angle.anotherFunction = function() { /* defined here */ };
return Angle;
});
这些函数包含相同的代码。
webpack.config.json 的相关部分:
/* some vars declared here truncated for brevity */
module.exports = function(env)
{
/* more stuff here */
resolve : {
alias: {
Cesium: path.resolve(__dirname, "scripts/Cesium/Cesium.js")
},
extensions: [".ts", ".tsx", ".js", ".json"]
},
module: {
rules : [
{
test: /\.js$/,
exclude: /(Cesium|node_modules)/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015'],
}
}
]
},
{
test: /\.tsx?$/,
exclude: /(Cesium|node_modules)/,
use: [
{
loader: 'awesome-typescript-loader'
}
]
},
/* and more */
和我的 tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"sourceMap": true
}
}
整个项目非常大,因此如果我将“allowJs”设置为 true,我会收到有关 Javascript 堆内存不足的错误。
Angle 被项目中的其他 Javascript 文件引用,如下所示:
define([
'./Angle',
],
function(
Angle
}
{
/* example function call */
functionName = function(i) {
return Angle.cyclic3dAxis(i);
};
});
如果我做错了什么,或者需要补充什么,请告诉我。感谢您的帮助!
最佳答案
转换后的文件中的导出结构与原始 JS 文件中的导出结构不匹配。模块应如下所示:
export function cyclic3dAxis(i: number): number{ /* function defined here */ }
export function anotherFunction(): number{/*defined here*/}
或者,如果您需要具有静态方法的类,则应使用 export = Angle;
导出该类:
class Angle
{
public static cyclic3dAxis(i: number): number{ /* function defined here */ }
public static anotherFunction(): number{/*defined here*/}
}
export = Angle;
关于javascript - 在 Javascript Webpack 项目中过渡到 Typescript(如何导出模块),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45443492/