This is not a duplicate of below questions which is dealing with browser specific questions. I'm expecting an answer whether
import / export
will work in Client side or not.
//lib.js
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//main.js
"use strict";
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Import Check</title>
</head>
<body>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Error that I'm getting in Chrome:
Tested Browser: Google Chrome Version 47.0.2526.106
BabelJS
) and code got transpiled. Will the import
/ export
file code snippet will work in the Client side or Server side (In node Server as require method)?MDN says
Note: This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel or Rollup.
For example after using babel on your code snippet you will get something like this:
//lib.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.square = square;
exports.diag = diag;
var sqrt = Math.sqrt;
exports.sqrt = sqrt;
function square(x) {
return x * x;
}
function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ main.js ------
'use strict';
var _lib = require('lib');
console.log((0, _lib.square)(11)); // 121
console.log((0, _lib.diag)(4, 3)); // 5
This code is enough to use in NodeJs. But to use in browser you need something like require.js or browserify. In this plunker I used require1k
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With