0

I published an 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. Something like this:

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

In my index.js file, I am exporting this like so:

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:

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:

"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. Any help is appreciated. Thanks.

darkhorse
  • 8,192
  • 21
  • 72
  • 148
  • 1
    did you forget to add `export` to `var elephant = ` in `js/script.js` – R Pasha Jul 12 '20 at 04:01
  • @RPasha So I just add `export` before the `var elephant`? Could you explain a bit more on this? – darkhorse Jul 12 '20 at 04:09
  • can you share your package so we can test? also, in your project you are using `ES import module ` syntax, and then in your sample you use `commonjs` i.d. `requiere` syntax. try using `module.exports.elephant = {......}` in your `js/script.js` and `module.exports = require("./js/script.js")` in your `index.js` – R Pasha Jul 12 '20 at 05:53
  • This time, I get `Uncaught ReferenceError: elephant is not defined` – darkhorse Jul 12 '20 at 14:47

1 Answers1

0

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.

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

Export your elephant from js/script.js

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

export default elephant;

In case of ES5 and older javascript version, use this syntax rather:

module.exports = elephant;

Neetigya Chahar
  • 683
  • 5
  • 14
  • Please export your `elephant`. – Neetigya Chahar Jul 12 '20 at 04:31
  • I tried your edited answer, but unfortunately still get the same error :( – darkhorse Jul 12 '20 at 04:39
  • Okay After adding export default to `elephant` in `js/script.js`. Just try this syntax in `index.js`: `export {default} from './js/script.js';`. Here `default` represents `elephant`. You can look for more references here: [link](https://stackoverflow.com/a/61960891/13192834). Will update the answer once it works. – Neetigya Chahar Jul 12 '20 at 04:48