Search code examples
javascriptnode.jswebpackecmascript-6commonjs

imported library function not defined from JavaScript webpack export


so I was following this https://webpack.js.org/guides/author-libraries/ from the web pack documentation, my file is just slightly different. No matter how I try to do this, I get various problems.

in my src/index.js file I have a simple function for example.

const Dinero = require('dinero.js')



export function calculateGrossRev(hudmonthly){
    // Calculates the yearly gross rev
    const hudonebr = Dinero({amount: hudmonthly, currency: 'USD'})
    .multiply(12);
    return hudonebr.getAmount();
}

In my package.json file I have.

{
  "name": "library",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "dinero": "^1.0.1",
    "lodash": "^4.17.21",
    "webpack": "^5.51.1",
    "webpack-cli": "^4.8.0"
  },
  "dependencies": {
    "dinero.js": "^1.9.0"
  }
}

In my webpack config file I have.

const path = require('path');

module.exports = {
  mode: "development",
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'dinero-calc.js',
    library: {
        name: "dineroNumbers",
        type: "umd",
    },
  },
 };

when I run "npm run build", I get the big bundled file, all looks well to me.

I then have an index.html file I run with Live Server in VScode.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TEST</title>
</head>
<h1>TEST</h1>
<script src="./dinero-calc.js"></script>
<script>
  console.log(window.dineroNumbers.calculateGrossRev(8200));
</script>
<body>

</body>
</html>

With the simple example from the docs I'm able to get the expected output from their expected function printed to the console, however with my imported function it says

index.html:11 Uncaught TypeError: Cannot read property 'calculateGrossRev' of       undefined at index.html:11

Solution

  • I think a problem is in the script source url <script src="./dinero-calc.js"></script>. Please, check paths of index.html and dinero-calc.js. According to your script tag, they should be in the same directory under dist folder.

    [Upd]

    First, install dinero.js which used in src/index.js.

    npm i dinero.js
    

    Also, dinero should be placed in dependencies, not devDependencies, because dinero.js used in your code.

    Second, call function like this

    Dinero.default({
        amount: hudmonthly,
        currency: "USD",
      }).multiply(12);