简体   繁体   English

使用导出默认值的 npm package 不是 function 错误

[英]Not a function error for an npm package using export default

I published an npm package.我发布了 npm package。 The directory structure is something like the following:目录结构类似于以下内容:

my-package
└── js/script.js
└── index.js

The js/script.js file contains an object that is the name of my library, lets say elephant . js/script.js文件包含一个 object ,它是我的库的名称,可以说elephant Something like this:像这样的东西:

var elephant = {
    function_1: function() {
        ...
    },
    function_2: function() {
        ...
    }
}

In my index.js file, I am exporting this like so:在我的index.js文件中,我像这样导出它:

import { elephant } from "./js/script.js";

export default elephant;

Once I published and installed my package, I tried to use it in my project using the following lines of code:一旦我发布并安装了我的 package,我尝试使用以下代码行在我的项目中使用它:

const elephant = require('my-package');
elephant.function_1();
elephant.function_2();

However, unfortunately when I run my dev server (in a Vue project), I get the following error:但是,不幸的是,当我运行我的开发服务器(在 Vue 项目中)时,我收到以下错误:

"TypeError: elephant.function_1 is not a function"

What am I doing wrong?我究竟做错了什么? The function has been clearly defined, and the export works, but the function is not detected. function 已明确定义,并且导出工作,但未检测到 function。 Any help is appreciated.任何帮助表示赞赏。 Thanks.谢谢。

I am not very sure if it works here or not, but I use this syntax which works pretty well.我不太确定它是否在这里有效,但我使用的语法效果很好。 You may try it on dev server.你可以在开发服务器上试试。 This is for index.js .这是针对index.js的。

export {
    elephant
} from './js/script.js';

Export your elephant from js/script.jsjs/script.js导出你的elephant

var elephant = {
    function_1: function() {
        ...
    },
    function_2: function() {
        ...
    }
}

export default elephant;

In case of ES5 and older javascript version, use this syntax rather:对于 ES5 和更早的 javascript 版本,请使用以下语法:

module.exports = elephant;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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