"Unexpected token" error when trying to use ECMA2015 module

0

I am testing the use of the ECMA2015 modules and something will be wrong because I can not use it. My code is as follows:

//Archivo libreria.js
export {unaFuncion, otraFuncion};

function unaFuncion() {
  console.log('Escrito desde unaFuncion');
}

function otraFuncion() {
  console.log('Escrito desde otraFuncion');
}

//Archivo main.js
import {unaFuncion, otraFuncion} from 'libreria';
unaFuncion();
otraFuncion();
<!DOCTYPE html>
<html>

<head>

    <title>Probando modulos</title>
    <script src="main.js"></script>
</head>

<body>

</body>

</html>

Testing in Chrome version 64.

    
asked by Serux 15.03.2018 в 02:11
source

2 answers

2

First, the tag script for a module has the syntax

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

If you omit type the browser assumes that it is classic javascript.

Second, in your main.js you have to import libreria.js with the relative path including extension:

import { unaFuncion, otraFuncion } from './libreria.js';

Using 'library', 'libreria.js' or './libreria' does not resolve to any file.

I'll leave an example running on Plunkr . (tested in Chrome, not all browsers support ES6 modules)

    
answered by 15.03.2018 / 13:08
source
1

The function import allows you to import (use the redundancy) the assignments (or values) that are defined in the module you are trying to import.

This function when reading the documentation that is in Mozilla

( link ).

We can read that it is only being implemented natively in some browsers, and when reviewing the ECMASCRIPT documentation,

( link )

We get the list of browsers that support the use of this function.

Safari 10.1.
Chrome 61.
Firefox 54 – behind the dom.moduleScripts.enabled setting in about:config.
Edge 16.

What happens if I want to use it ?, I must apply a transpiler, including the Mozilla documentation:

Typescript, Babel, Webpack y Parcel

Link of the response of the site in English:

( link )

    
answered by 15.03.2018 в 14:23