7

I am trying to transpile this simple code so as to use in browser, but its not working and getting Uncaught ReferenceError: require is not defined at line require('uniq')(array);

I know browser ( chrome in my case ) doesn't support require, but I thought that's what babel supposed to do.

I can use webpack or browserify, but this time I am trying my hands on Babel and come across this issue.

package.json

"devDependencies": { "@babel/cli": "^7.11.5", "@babel/core": "^7.11.5", "@babel/preset-env": "^7.11.5" }, "dependencies": { "@babel/polyfill": "^7.11.5", "uniq": "^1.0.1" } 

index.js

const array = [1,1,2,2,3,5] require('uniq')(array) document.querySelector('p').innerText = array 

using babel to transpile
npx babel index.js --out-file index2.js

index2.js ( generated by babel )

"use strict"; const array = [1, 1, 2, 2, 3, 5]; require('uniq')(array); document.querySelector('p').innerText = array; 

babel.config.json

{ "presets": [ [ "@babel/env", { "targets": { "edge": "17", "firefox": "60", "chrome": "67", "safari": "11.1", }, "useBuiltIns": "usage", "corejs": "3.6.4", } ] ] } 

index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Babel Example</title> </head> <body> <h1>Babel Example</h1> <p><p> <script src="index2.js"></script> </body> </html> 
3
  • "but I thought thats what babel supposed to do" No. Babel just transforms from one JavaScript version to another. It does not concerned with module loading/processing. Commented Sep 1, 2020 at 6:49
  • Babel just transforms your code to commonjs which is not runnable on browser. Consider to write as esmodule which can run on browser by specify module attribute on script tag. Commented Sep 1, 2020 at 7:11
  • 1
    You need to use a bundler like webpack for this. Babel does not provide this functionality, it is a language transpiler. Commented Sep 1, 2020 at 7:41

1 Answer 1

-1

looks like the same issue was discussed here https://github.com/babel/gulp-babel/issues/117

You just need to add the env preset --presets=@babel/preset-env https://babeljs.io/docs/en/babel-cli#using-presets

Your transpile command should become npx babel index.js --out-file index2.js --presets=@babel/preset-env

Sign up to request clarification or add additional context in comments.

2 Comments

I tried as per your suggestion, no change in output, and the presets parameter you suggested, is already there in babel.config.json I posted above.
hmm yeah actually, might be more complicated, this is a similar question: stackoverflow.com/questions/31593694/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.