Consider the following example code (and maybe I am doing it wrong?)
var FlareCurrency = {
};
export {FlareCurrency};
I have the following task:
gulp.task("compile:add-new-currency-minified", function(){
return gulp.src('src/add-new-currency/**/*.js')
.pipe(babel())
.pipe(concat('Flare-AddNewCurrency.js'))
.pipe(uglify({"preserveComments": "all"}))
.pipe(gulp.dest('dist/minified/'));
});
When I run this I get the following:
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var FlareCurrency={};exports.FlareCurrency=FlareCurrency;
For the fun of it, I wanted to run it in the console, yes I know it does nothing but I didn't expect to see this:
Uncaught ReferenceError: exports is not defined(…)
The non minified version:
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var FlareCurrency = {};
exports.FlareCurrency = FlareCurrency;
throws the same error. Ideas?
That is not actually a babel issue, you are just trying to run CommonJS code (transpiled from ES6 export) in the browser without preparation. CommonJS doesn't run on the browser, you need to use a tool to package it for the browser, such as Webpack or Browserify.
Just by coincidence this week I created a small project on Github that shows a setup of Gulp + ES6 code (using export) + Babel + Webpack: gulp-es6-webpack-example.
In my example you can load JS code on the browser either synchronously (pre-loaded) or asynchronously (lazy-loaded).
I fix it just set se6 for settings gulp-typescript package:
import gulp from 'gulp';
import ts from 'gulp-typescript';
import uglify from 'gulp-uglify';
import browserSync from 'browser-sync';
export const scripts = () => {
return gulp.src(['app/scripts/*', '!app/scripts/modules/'])
.pipe(ts({
noImplicitAny: true,
target: "es6" // <<< THIS
}))
.pipe(uglify())
.pipe(gulp.dest('dist/scripts/'))
.pipe(browserSync.stream())
}
Besides you have to set type="module" for connect your js file in html.
<script type="module" src="scripts/index.js"></script>
Related
I have a gulpfile.js that watch file changes in a folder. Everything was working fine until I upgraded from Gulp 3.9.1 to 4.0.2. When upgrading the Gulp, I also upgraded my node.js to the latest v12.17.0
Here is my gulp task that bundles the js files
var gulp = require("gulp"),
concat = require("gulp-concat"),
filter = require('gulp-filter'),
merge = require("merge-stream");
gulp.task("min:js", function () {
var tasks = [];
var task = gulp.src(['path_1/**/*.js', 'path_2/**/*.js'], { base: "." })
.pipe(filter('**/*.js'))
.pipe(concat('output.js'))
.pipe(gulp.dest("."));
tasks.push(task);
return merge(tasks);
});
The task generates the following code
// More Js code...
import { setTimeout } from "timers";
'use strict';
// more js code.....
But the line import { setTimeout } from "timers"; is throwing the following error
SyntaxError: import declarations may only appear at the level of a
module
How can I fix this error?
The above problem might be caused due to the attempt to import setTimeout as a module.
setTimeout is a standard javascript function and it need not be imported explicitly. Therefore, removing the import statement may solve the issue.
If the above step does not fix the issue, then the following may be tried:
Add type="module" attribute to the HTML script tag that includes the module.
<script type="module" src="my-module.js"></script>
I am setting up a boilerplate running Gulp with Babel. I have created 2 simple files (app.js and Caller.js) to test the environment.
Caller.js:
export default class Caller {
constructor() {
//
}
SayHello() {
alert("Hello!!");
}
}
App.js:
import Caller from './Caller.js';
let x = new Caller();
x.SayHello();
App.js is referenced in index.html along with:
<script src="/js/Caller.js"></script>
<script src="/js/app.js"></script>
My Gulp task looks like this:
gulp.task('js', () => {
pump([
gulp.src(src.js),
plumber(err => console.error(err)),
babel({ presets: ['es2015', 'es2017'] }),
gulp.dest(dest.js),
browserSync.stream()
]);
});
Note: I am trying to be as supportive of older browsers as possible, so I want to include ES2015.
What I find is that when I include es2015, rather than es2017 alone, I get the following errors:
ReferenceError: exports is not defined
ReferenceError: require is not defined
My understanding is that it is possible to transpile this code into ES2015 compatible code, yet if I remove ES2015 from the Babel presets in Gulp it works fine.
Why?
Consider the following example code (and maybe I am doing it wrong?)
var FlareCurrency = {
};
export {FlareCurrency};
I have the following task:
gulp.task("compile:add-new-currency-minified", function(){
return gulp.src('src/add-new-currency/**/*.js')
.pipe(babel())
.pipe(concat('Flare-AddNewCurrency.js'))
.pipe(uglify({"preserveComments": "all"}))
.pipe(gulp.dest('dist/minified/'));
});
When I run this I get the following:
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var FlareCurrency={};exports.FlareCurrency=FlareCurrency;
For the fun of it, I wanted to run it in the console, yes I know it does nothing but I didn't expect to see this:
Uncaught ReferenceError: exports is not defined(…)
The non minified version:
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var FlareCurrency = {};
exports.FlareCurrency = FlareCurrency;
throws the same error. Ideas?
That is not actually a babel issue, you are just trying to run CommonJS code (transpiled from ES6 export) in the browser without preparation. CommonJS doesn't run on the browser, you need to use a tool to package it for the browser, such as Webpack or Browserify.
Just by coincidence this week I created a small project on Github that shows a setup of Gulp + ES6 code (using export) + Babel + Webpack: gulp-es6-webpack-example.
In my example you can load JS code on the browser either synchronously (pre-loaded) or asynchronously (lazy-loaded).
I fix it just set se6 for settings gulp-typescript package:
import gulp from 'gulp';
import ts from 'gulp-typescript';
import uglify from 'gulp-uglify';
import browserSync from 'browser-sync';
export const scripts = () => {
return gulp.src(['app/scripts/*', '!app/scripts/modules/'])
.pipe(ts({
noImplicitAny: true,
target: "es6" // <<< THIS
}))
.pipe(uglify())
.pipe(gulp.dest('dist/scripts/'))
.pipe(browserSync.stream())
}
Besides you have to set type="module" for connect your js file in html.
<script type="module" src="scripts/index.js"></script>
I have a Typescript+Node+Angular2+Electron app and currently trying to run tests for node classes, written also in Typescript.
For building the application and running it within electron I use following tsconfig:
"compilerOptions": {
"module": "system",
"target": "es6",
...
}
So as you can see, it's using systemjs and compiling TS into JS-es6. It works fine, application itself is working.
Now I need Jasmine to come on board. I installed this npm package, updated my gulp tasks to run gulp-jasmine for just 1 file:
gulp.task('jasmine', function() {
gulp.src('./test/test.js')
.pipe(jasmine())
});
This is how my test.js looks like:
System.register(["./models-src/app/models/pathWatch/pathWatch"], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var pathWatch_1;
return {
setters:[
function (pathWatch_1_1) {
pathWatch_1 = pathWatch_1_1;
}],
execute: function() {
describe("Run Application:", () => {
it("starts", () => {
var pw1 = new pathWatch_1.PathWatch();
expect(true).toEqual(true);
});
});
}
}
});
So, nothing special, 1 import-1test-1assert, wrapped with SystemJs stuff.
When I try to run this test, I have an error: "System is not defined".
My questions are:
1) Is it possible to run jasmine tests, using systemjs loader inside?
2) If it's possible, do I need to install/configure some additional stuff?
3) I tried to compile TS using Module="commonjs" and it's working. But I don't want to compile my source differently for tests and build. Why it's working fine with commonjs without any additional manipulations?
4) Also I tried to compile TS using Module="es6". It's not working, I have an error "Unexpected reserved word". Is it possible to run jasmine tests written in js es6 without transpiling them into es5?
Thanks a lot!
1) Is it possible to run jasmine tests, using systemjs loader inside?
2) If it's possible, do I need to install/configure some additional
stuff?
You mean, run jasmine tests in node using systemjs as a loader? I don't think jasmine supports using systemjs instead of require for loading modules. So your tests need to be in commonjs, but test code can use SystemJS to load and test application code. Something like this in test.js could work, provided that systemjs is configured properly and can find pathWatch module:
describe("Run Application:", () => {
it("starts", (done) => {
var system = require('systemjs');
system.config({
// systemjs config here
//
});
system.import('path-to-path-watch-module').then(pathWatch => {
var pw = new pathWatch.PathWatch();
expect(true).toEqual(true);
done();
});
});
});
system.import is asynchronous, so all jasmine tests need to be async too.
3) I tried to compile TS using Module="commonjs" and it's working. But
I don't want to compile my source differently for tests and build. Why
it's working fine with commonjs without any additional manipulations?
Because then there is no reference to System in the compiled code - it uses module.exports like any other node module and can be loaded as is by jasmine.
4) Also I tried to compile TS using Module="es6". It's not working, I
have an error "Unexpected reserved word". Is it possible to run
jasmine tests written in js es6 without transpiling them into es5?
Module="es6" requires a runtime that supports es6 import and export, so it needs a transpiler and module loader before it can run on current version of node.
I have an existing application where I have AMD modules defined using RequireJS. I use "text" and "i18n" plugins for requirejs extensively in my project.
I have been experimenting with ES6 modules lately and would like to use them while creating new modules in my application. However, I want to reuse the existing AMD modules and import them while defining my ES6 modules.
Is this even possible? I know Traceur and Babel can create AMD modules from ES6 modules, but that only works for new modules with no dependency on existing AMD modules, but I could not find an example of reusing the existing AMD modules.
Any help will be appreciated. This is a blocker for me right now to start using all ES6 goodies.
Thanks
Yes, it can be done. Create a new application with the following structure:
gulpfile.js
index.html
js/foo.js
js/main.es6
node_modules
Install gulp and gulp-babel. (I prefer to install gulp locally but you may want it globally: that's up to you.)
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Something</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.js"></script>
<script>
require.config({
baseUrl: "js",
deps: ["main"]
});
</script>
</head>
<body>
</body>
</html>
gulpfile.js:
"use strict";
var gulp = require('gulp');
var babel = require('gulp-babel');
gulp.task("copy", function () {
return gulp.src(["./js/**/*.js", "./index.html"], { base: '.' })
.pipe(gulp.dest("build"));
});
gulp.task("compile-es6", function () {
return gulp.src("js/**/*.es6")
.pipe(babel({"modules": "amd"}))
.pipe(gulp.dest("build/js"));
});
gulp.task("default", ["copy", "compile-es6"]);
js/foo.js:
define(function () {
return {
"foo": "the value of the foo field on module foo."
};
});
js/main.es6:
import foo from "foo";
console.log("in main: ", foo.foo);
After you've run gulp to build the application, open the file build/index.html in your browser. You'll see on the console:
in main: the value of the foo field on module foo.
The ES6 module main was able to load the AMD module foo and use the exported value. It would also be possible to have a native-AMD module load an ES6 module that has been converted to AMD. Once Babel has done its work, they are all AMD modules as far as an AMD loader is concerned.
In addition to #Louis's answer, assuming you already have a bunch of third party libraries specified in require.js configuration, in your new ES6 modules, whenever you are importing a module, be it amd or es6, you'll be fine as long as you keep the imported module name consistent. For example:
Here is the gulpfile:
gulp.task("es6", function () {
return gulp.src("modules/newFolder//es6/*.js")
.pipe(babel({
"presets": ["es2015"],
"plugins": ["transform-es2015-modules-amd"]
// don't forget to install this plugin
}))
.pipe(gulp.dest("modules/newFolder/build"));
});
Here is the es6 file:
import d3 from 'd3';
import myFunc from 'modules/newFolder/es6module'
// ...
This will be compiled to sth like this:
define(['d3', 'modules/newFolder/es6module'], function (_d, _myFunc) {
'use strict';
// ...
});
as long as the module in define(['d3', 'modules/newFolder/es6module'], ... of the compiled file is fine in a original AMD file, it should work with under existing require.js setup, such as compress files etc.
In terms of #coderC's question about require.js loaders, I was using i18n!nls/lang in AMD modules, at first I thought it would be a really tricky thing to find an alternative of AMD plugin loaders in ES6 modules, and I switched to other localization tools such as i18next. But it turned out that it's okay to do this:
import lang from 'i18n!nls/lang';
// import other modules..
because it will be compiled by gulp task to sth like:
define(['d3', 'i18n!nls/lang'], function (_d, _lang) {
// ....
This way, we don't have to worry about the require.js loader.
In a nutshell, in ES6 modules, if you want to use existing AMD plugin/modules, you just need to ensure the compiled file is conformed with the existing setup. Additionally, you can also try the ES6 module bundler Rollup to bundle all the new ES6 files.
Hope this can be helpful for those who are trying to integrate ES6 syntax in project.
A few changes for the latest version of babel:
First, babel({"modules": "amd"}) doesn't work with the latest version of babel. Instead, use babel({"plugins": ["#babel/plugin-transform-modules-amd"]}). (You'll need to install that plugin as a separate module in npm, i.e. with npm install --save-dev #babel/plugin-transform-modules-amd.)
Second, the syntax for gulp.task no longer accepts arrays as its second argument. Instead, use gulp.parallel or gulp.series to create a compound task.
Your gulpfile will end up looking like this:
"use strict";
var gulp = require('gulp');
var babel = require('gulp-babel');
gulp.task("copy", function () {
return gulp.src(["./js/**/*.js", "./index.html"], { base: '.' })
.pipe(gulp.dest("build"));
});
gulp.task("compile-es6", function () {
return gulp.src("js/**/*.es6")
.pipe(babel({"plugins": ["#babel/plugin-transform-modules-amd"]}))
.pipe(gulp.dest("build/js"));
});
gulp.task("default", gulp.parallel("copy", "compile-es6"));