Trying to use import/export in ES6 (with babel compile)

Viewed 4836

Here are the files for my app which uses babel to compile the ES6 in main.js to ES5 in main.bundle.js

enter image description here

Here is my babel.rc file (hidden):

{
    "presets": ["@babel/preset-env"]
}

Here is my package.json file with all my node modules (devDependencies):

{
  "name": "es6-tutorial",
  "version": "1.0.0",
  "description": "ES6 tutorial",
  "main": "index.js",
  "scripts": {
    "babel": "babel js/main.js -o build/main.bundle.js",
    "start": "http-server",
    "watch": "babel js/main.js -o build/main.bundle.js --watch"
  },
  "author": "me",
  "license": "ISC",
  "devDependencies": {
    "@babel/preset-env": "^7.2.0",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.3",
    "babel-preset-es2015": "^6.24.1",
    "http-server": "^0.11.1"
  }
}

Right now to start the compile from ES6 to ES5 I navigate (cd) to the root of this directory and I set up a watch to compile automatically (npm run watch)

This works fine except now I also have functions in myFunctions.js that I want to export and import into main.js

When I add this export/import I notice that the compiled file, main.bundle.js, adds this:

`var _myFunctions = require('myFunctions.js');`

Then when I go to run the app I get an error in the console:

`Uncaught ReferenceError: require is not defined
at main.bundle.js:9`

After researching this, I think I need to add some sort of plugin for Babel : https://babeljs.io/docs/en/plugins#modules to handle the export/import (is that right?) but I'm not sure which one I should use and I tried a few but I cannot get any to work after the npm install.

Also, I understand that I do NOT need to add the require.js library right?

0 Answers
Related