0

So I'm trying to connect my Javascript application to Firebase. I understand that I need to use a bundler to do this, and my preferred method is Parcel.JS. I run my Parcel.JS script with the following code in my package.json file:

  "main": "./public/js/bundle.js",
  "scripts": {
    "watch:js": "parcel watch ./public/js/index.js --dist-dir ./public/js",

This is the code in my index.js file:

import { initializeApp } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';

const firebaseConfig = {
  apiKey: '',
  authDomain: '',
  projectId: '',
  storageBucket: '',
  messagingSenderId: '',
  appId: '',
  measurementId: '',
};

const app = initializeApp(firebaseConfig);

const analytics = getAnalytics(app);

Parcel.JS bundles it up into bundle.js as expected, and I reference it at the bottom of my index.pug file as follows:

script(src='/js/bundle.js')

When the page loads, I check the console in Chrome and see the following error message:

Uncaught ReferenceError: require is not defined
    at bundle.js:1

Can anyone tell me what I'm doing wrong here? I'm a bit lost.

Chris Clark
  • 488
  • 2
  • 19
  • The error you received is because you didn't define something on line 1 in your `bundle.js` file. – Izzi Oct 08 '21 at 08:38

1 Answers1

1

You probably don't want to use the "main" field in package.json. According to the documentation, this is intended for people who develop libraries (e.g. npm packages that are consumed by others), which doesn't sound like you. Specifically, the "main" field tells parcel to output a commonjs bundle at that location, which would help explain why you are seeing errors about require calls, which won't run in the browser.

Another possible source of trouble is the fact that your dist-dir directory is the same location as your source js (./public/js) - I havn't been able to test this because npm is down at the moment, but what I think that might cause parcel to overwrite your source files?

I'd recommend removing the main field from package.json and moving your source code to a different directory than the --dist-dir target.

Andrew Stegmaier
  • 3,429
  • 2
  • 14
  • 26