简体   繁体   中英

Typescript declared static class method is not a function

I created an es6 library for some of my projects.

When I import this library all static functions raise an error.

This is an example.

My Class (es6) :

class JsonSerializer {
    static toJson(node) { /* some code */ }
}

export default JsonSerializer

Typescript definition file :

export class JsonSerializer {
    static toJson(root: Node): any

    static fromJson(config: any): Node
}

I import my class like this

import {JsonSerializer} from 'ls-serializer'

When I try to use toJson static method.

And its give me following error :

_lsSerializer.JsonSerializer.toJson is not a function

I've same error for all static method.

Did I miss something ?

EDIT

This is my library webpack config :

const path = require('path');

module.exports = {

    entry : {
        serializer : './src/serializer.js'
    },

    output : {
        path     : path.resolve(__dirname, 'dist'),
        filename : '[name].bundle.js',
        libraryTarget: 'commonjs-module'
    },

    resolve : {
        extensions : ['.js', '.jsx'],

        alias : {
            '@' : path.resolve(__dirname, 'src'),
            '~' : path.resolve(__dirname, 'examples')
        }
    },

    devServer : {
        contentBase : path.resolve(__dirname, 'dist'),
        compress    : true,
        port        : 9000
    },

    module : {
        rules : [{
            test    : /\.(js|jsx)$/,
            exclude : /node_modules/,
            loader  : 'babel-loader'
        }, {
            test : /\.(html)$/,
            use  : {
                loader  : 'html-loader',
                options : {
                    attrs : [':data-src']
                }
            }
        }]
    },

    devtool : 'source-map',

    mode : 'development'
};

And this is ./src/serializer.js file code :

import JsonSerializer from './serializers/JsonSerializer'

export {
    JsonSerializer, /* other exports*/
}

I guess the file with the class is called ls-serializer.ts .

You have to use it like this:

import JsonSerializer from './ls-serializer'

JsonSerializer.toJson(...)

Or you can avoid default :

// ls-serializer.ts
export class JsonSerializer {
    static toJson(node) { /* some code */ }
}

And export the class like this:

import {JsonSerializer} from './ls-serializer'

JsonSerializer.toJson(...)

I've found the problem and it's a little pitiful...

In my code toJson method is named toJSON with capitalize part... And in camel case in my typescript declaration file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM