You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何导出/导入构造函数?解决‘test is not a constructor’报错

问题分析与解决方案

你的报错核心是导入方式与导出逻辑不匹配,原UMD导出的是默认值,但你使用了命名导入,导致获取的test是undefined,最终触发test is not a constructor错误。以下是具体修复方案:


方案一:修改导入方式(适配现有导出)

你的UMD代码将test作为默认导出赋值给module.exports,因此ES模块中需使用默认导入:

import Test from 'path/to/test'

const myTest = new Test();

注:JS惯例中构造函数首字母大写,建议把test改为Test,避免与普通函数混淆


方案二:修改UMD导出为命名导出(适配你的导入写法)

如果想保留import {test}的导入方式,需将UMD导出改为命名导出格式:

(function(factory) {
    // 兼容CommonJS与AMD环境的命名导出
    if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = { test: factory() };
    } else if (typeof define === 'function' && define.amd) {
        define({ test: factory() });
    }
}(function() {
    function test() {
        this.param = 'This is a test';
        this.init = function() {
            console.log(this.param)
        };
        this.init();
    }
    return test;
}));

修改后,你原有的导入代码import {test} from 'path/to/test'即可正常工作,实例化不会再报错。


额外优化:标准UMD写法(兼容更多环境)

如果需要同时支持AMD、CommonJS、全局变量三种环境,可使用更规范的UMD模板:

(function(root, factory) {
    if (typeof define === 'function' && define.amd) {
        define([], factory);
    } else if (typeof module === 'object' && module.exports) {
        // 同时支持默认导出与命名导出
        const Test = factory();
        module.exports = Test;
        module.exports.test = Test;
    } else {
        // 浏览器全局变量环境
        root.test = factory();
    }
}(typeof self !== 'undefined' ? self : this, function() {
    function Test() {
        this.param = 'This is a test';
        this.init = function() {
            console.log(this.param);
        };
        this.init();
    }
    return Test;
}));

这种写法下,不管是默认导入、命名导入还是CommonJS的require方式,都能正确获取构造函数并实例化。


内容的提问来源于stack exchange,提问作者user19967625

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:10:27