Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript ES6 import and export functionality in Codepen projects

I am trying to use the Javascript ES6 import/export functionality in my Codepen project, and I thought it was supported based on some articles I read, but I am having trouble getting it to work. I have set my Codepen project to use Webpack and Babel to process my javascript file, and even tried using Chrome Canary to see if that would support ES6 (to no avail).

In my Codepen project, I wrote a basic example exporting a string variable from one file:

//data.js
export let firstName = 'George';

Then importing it into my primary javascript file to log in the console:

//index.js
import firstName from "./data";
console.log(FirstName);

Unfortunately, the Chrome console is reporting the error:

Uncaught VM3034 index.js:1
SyntaxError: Unexpected token import

Does anyone know how to get this to work, if possible? I even found another example of a Codepen project using ES6 import/export successfully, but I'm not sure what I'm doing differently to get the error. Any help would be much appreciated.

like image 987
Sergei Wallace Avatar asked Oct 08 '17 21:10

Sergei Wallace


2 Answers

Here's a working example:

Import https://codepen.io/oneezy/pen/jzWjLe

import { getNodes } from 'https://codepen.io/oneezy/pen/BrjgdY.js';

let videoHTML = getNodes(`
  <div class="widget">
    <h2>I'm a widget!</h2>
    <p>I do widgeting.</p>
  </div>
`);

document.body.appendChild(videoHTML[0]);


Export https://codepen.io/oneezy/pen/BrjgdY

export function getNodes(str) { 
  return new DOMParser().parseFromString(str, 'text/html').body.childNodes;
}
like image 116
Oneezy Avatar answered Sep 24 '22 15:09

Oneezy


Your project was using webpack/babel and I suspect that wasn't set up or working quite right. This answer will not address that. Instead, I'll describe the setup for using bare bones ES6. Because it's 2018.

Codepen has added some documentation on how to get modules working at https://blog.codepen.io/2017/12/26/adding-typemodule-scripts-pens/

They mention that for Codepen projects you need to designate that you are using modules by adding type="module" to the <script> tag. So in index.html you need to change

  <script src="scripts/index.js"></script>

to

  <script src="scripts/index.js" type="module"></script>

In my working version, data.js looks like this:

function foo(str) { console.log(`foo prints ${str}`); }

let firstName = 'George'

export { foo, firstName };

index.js looks like this:

import {foo, firstName} from './data.js';

foo(firstName);

(By the way, I would have thought that './data' would have worked in the import statement. But no, you need './data.js')

like image 25
brainjam Avatar answered Sep 23 '22 15:09

brainjam