grahamcracker1234
grahamcracker1234

Reputation: 609

"SyntaxError: import not found" with ES6 babel-compiled module

I have the following project structure:

├── node_modules
│   └── (dependencies, etc.)
├── dist
│   └── bundle.js
├── src
│   └── bundle.js
├── index.html
├── main.js
├── .babelrc
├── package-lock.json
└── package.json

My .babelrc contains the following:

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

I have the following included in my package.json:

"browserslist": "defaults and supports es6-module"

My source bundle.js contains the following:

const foo = "foo";
export default foo;

My distribution bundle.js contains the following when compiled with babel:

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var foo = "foo";
var _default = foo;
exports["default"] = _default;

I import this compiled bundle in my main.js:

import foo from "/dist/bundle.js";
console.log(foo);

And then include main.js at the bottom of the body tag in index.html

<script type="module" src="/main.js"></script>

After running the page, the console gives me the following error:

Uncaught SyntaxError: import not found: default

I do not think that I am configuring babel correctly, but I cannot figure out out to do so properly. Any help is appreciated.

Upvotes: 0

Views: 1580

Answers (1)

brokensandals
brokensandals

Reputation: 116

I think the issue is that you're using ES6 module syntax in the browser, but the file you're importing has been transpiled not to use ES6 module syntax. Note that if you paste your source bundle.js file into dist/bundle.js it works fine.

One way to fix this is to change your .babelrc file as follows, so that the module syntax won't be transpiled:

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

An alternative approach would be to also transpile main.js, and remove the type="module" from your script tag.

Upvotes: 1

Related Questions