I am using parcel V2.7.1 so that i can interact my frontend script with my backend express app. I imported axios
which is an npm package, but anytime i but anytime i run parcel and build I get and error message on the browser console stated Uncaught referenceError: require is not defined
. I checked my bundle.js file and i find some lines with the require
keyword. In summary anytime there is a require
keyword in my main bundle file (bundle.js) due to an npm package import from my source file (index.js) i get the error Uncaught referenceError: require not defined
.
I set "browserslist": "> 0.25%
But am not sure if that even affected anything
I also set "engines": { "browsers":"> 0.25% }
Please what can i do now cause am out of options.. i have read through the parcel.js documentation but nothing to help me
Basically parcel has ability to compile the code in both native ES module and CommonJS.
Both of these compile code for node environment and can't be run on browsers and will give error
Solution
To get the code, for the browser, a good way is that to not provide main field in the package.json. And instead write your target output directory in the target field. Like this:-
"targets": {
"default": {
"distDir": "./public"
}
}
Also specify the browserlist field to specify the browser. Here is an example of using browserlist field:-
"browserslist": "> 0.5%"
You can provide the source directory in source field like this:-
"source": "resources/script.js",
You can study in detail for different possible targets in parcel documentation.
I was facing your same issue. Solved it making some changes to the package.json file.
As mentioned in the parcel's documentation, try to add, if you have not already:
"targets": {
"main": false
},
(https://parceljs.org/features/targets/)
Next, define "browserslist": "> 0.25%"
or "browserslist": "last 2 versions"
right after "targets".
Delete the folder where the bundled code is located and use
parcel build ./js/file/to/bundle.js --dist-dir ./path/where/folder/is/supposed/to/be
to generate your brand new bundled js folder without require() errors.
In the end, your package.json file should be like this:
"name": "app-name",
"version": "1.0.0",
"description": "",
"main": "app.js",
"targets": {
"main": false
},
"browserslist": "> 0.25%",
"engines": {
"node": ">=16.0.0"
},
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"debug": "ndb server.js",
"watch:js": "parcel serve ./public/js/index.js --dist-dir ./public/js/bundled",
"build:js": "parcel build ./public/js/index.js --dist-dir ./public/js/bundled"
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With