Monday, 18 April 2022

Can't access exported functions in bundled .js file using esbuild

I want to create a library using TypeScript. It should be available for Node and Browser environments.

I started with the package.json file and installed esbuild as a dependency and typescript as a dev dependency. The result is

{
  "name": "my-lib",
  "version": "1.0.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "tsc && esbuild ./dist/lib/index.js --bundle --minify --sourcemap --outfile=./bundle/index.js"
  },
  "dependencies": {
    "esbuild": "0.14.36"
  },
  "devDependencies": {
    "typescript": "4.6.3"
  }
}

The tsconfig.json file contains

{
  "compilerOptions": {
    "baseUrl": ".",
    "declaration": true,
    "esModuleInterop": true,
    "lib": [ "dom", "esnext" ],
    "module": "commonjs",
    "outDir": "dist",
    "resolveJsonModule": true,
    "strict": true,
    "target": "es2019",
  },
  "include": [
    "./**/*.ts"
  ],
  "exclude": [
    "./dist"
  ]
}

Inside the root directory I have a lib directory holding an index.ts file which exports all the "public" functions, e.g.

const sum = function (a: number, b: number): number { return a + b; };

export { sum };

Besides that I have a test directory right next to the lib directory, holding some .ts files. I want to test the build script and added the following index.html to the root directory

<!DOCTYPE html>
<html>
    <head>
      <script type='text/javascript' src='./bundle/index.js'></script>
    </head>
    <body>
        <div>
            Loading bundle...
        </div>
    </body>
</html>

<script type="text/javascript">
window.onload = () => {
  console.log('ready');

  const result = sum(1, 2);

  console.log({ result });

  const anotherResult = window.sum(1, 2);

  console.log({ anotherResult });
};
</script>

Unfortunately I get an Uncaught ReferenceError because it is not able to find the function sum. The folder structure before running npm install && npm run build is

enter image description here

Does someone know what's wrong or missing here?



from Can't access exported functions in bundled .js file using esbuild

No comments:

Post a Comment