Reading the answer https://es.stackoverflow.com/a/1371/353 I saw how it is possible to import modules using ES6
.
However, from what I've read, it's not implemented in browsers yet, so it's necessary to use a transpiler like Babel.js
.
My problem now is that I am trying an example and I still get this error Uncaught SyntaxError: Unexpected token import
despite running npm run build
as it appears in the Babel CLI docs and installing the AMD plugin AMD plugin
This is what the example directory looks like:
And this is the code:
src/functions.js
export function sum (a, b) {
return a + b
}
src/main.js
'use strict'
import {sum} from 'functions'
let a = 10
let b = 5
console.log(sum(a, b))
dist/main.js
'use strict';
import { sum } from 'functions';
let a = 10;
let b = 5;
console.log(sum(a, b));
dist/main.js
export function sum(a, b) {
return a + b;
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ES6 Getting Started</title>
<meta name="description" content="An example of how to use ES6">
</head>
<body>
<p>
View the console
</p>
<script src="dist/main.js">
</script>
</body>
</html>
package.json
{
"name": "my-project",
"version": "1.0.0",
"scripts": {
"build": "babel src -d dist"
},
"devDependencies": {
"babel-cli": "^6.4.5"
}
}
I think the plugin that converts modules
ES6
into modules is not working for youAMD
I will make sure that
.babelrc
the plugin is included in the archive and you have installed the npm packageAfter doing this, when compiling with
babel
, the resulting files should look like this:dist/main.js
dist/functions.js
Finally, to load the AMD modules, you have to use , the index.html
requirejs
file would look like this