6

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>
GLK
  • 875
  • 2
  • 9
  • 25
  • *"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. – Felix Kling Sep 01 '20 at 06: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. – tmhao2005 Sep 01 '20 at 07:11
  • 1
    You need to use a bundler like webpack for this. Babel does not provide this functionality, it is a language transpiler. – Andy Sep 01 '20 at 07:41

1 Answers1

-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

  • 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. – GLK Sep 01 '20 at 07:03
  • hmm yeah actually, might be more complicated, this is a similar question: https://stackoverflow.com/questions/31593694/do-i-need-require-js-when-i-use-babel – James Rushford Sep 01 '20 at 07:13