Babel not working as expected, Error : Uncaught ReferenceError: require is not defined

Viewed 9947

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>
1 Answers
Related