简体   繁体   English

如何使用 npm ZEFE90A8E604A7C840E888D03D 中的 module.exports 导出 JavaScript object

[英]How to export a JavaScript object using module.exports in an npm package?

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";

module.exports = elephant;

Once I published and installed my package, I tried to pull it in my project using the following line of code:发布并安装 package 后,我尝试使用以下代码行将其拉入我的项目:

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

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

Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

I assume this is referring to the third line in the index.js file.我假设这是指index.js文件中的第三行。 How can I fix this issue?我该如何解决这个问题? How do I export my object variable and use it in my node project?如何导出我的 object 变量并在我的节点项目中使用它? Thanks for any help!谢谢你的帮助!

You can't mix import and module.exports你不能混合importmodule.exports

use export default elephant instead of module.exports = elephant;使用export default elephant而不是module.exports = elephant;

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

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