SyntaxError: Unexpected token { in Gruntfile.js - gruntjs

I don't manage to configure grunt. I have followed all the steps from Magento2 but I receive this syntax error.
grunt
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Unexpected token {
Warning: Task "default" not found. Use --force to continue.
Aborted due to warnings.
I have reinstalled both the grunt and the node.js, but it doesn't work.
Has anybody had the same problem?
Below you can see the Gruntfile.js ( that is original) posted.
Is it an error of this file or is there another problem?
Gruntfile.js
module.exports = function (grunt) {
'use strict';
var _ = require('underscore'),
path = require('path'),
filesRouter = require('./dev/tools/grunt/tools/files-router'),
configDir = './dev/tools/grunt/configs',
tasks = grunt.file.expand('./dev/tools/grunt/tasks/*'),
themes;
filesRouter.set('themes', 'dev/tools/grunt/configs/themes');
themes = filesRouter.get('themes');
tasks = _.map(tasks, function(task){ return task.replace('.js', '') });
tasks.push('time-grunt');
tasks.forEach(function (task) {
require(task)(grunt);
});
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, configDir),
init: true,
jitGrunt: {
staticMappings: {
usebanner: 'grunt-banner'
}
}
});
_.each({
/**
* Assembling tasks.
* ToDo: define default tasks.
*/
default: function () {
grunt.log.subhead('I\'m default task and at the moment I\'m empty, sorry :/');
},
/**
* Production preparation task.
*/
prod: function (component) {
var tasks = [
'less',
'autoprefixer',
'cssmin',
'usebanner'
].map(function(task){
return task + ':' + component;
});
if (typeof component === 'undefined') {
grunt.log.subhead('Tip: Please make sure that u specify prod subtask. By default prod task do nothing');
} else {
grunt.task.run(tasks);
}
},
/**
* Refresh themes.
*/
refresh: function () {
var tasks = [
'clean',
'exec:all'
];
_.each(themes, function(theme, name) {
tasks.push('less:' + name);
});
grunt.task.run(tasks);
},
/**
* Documentation
*/
documentation: [
'replace:documentation',
'less:documentation',
'styledocco:documentation',
'usebanner:documentationCss',
'usebanner:documentationLess',
'usebanner:documentationHtml',
'clean:var',
'clean:pub'
],
'legacy-build': [
'mage-minify:legacy'
],
spec: function (theme) {
var runner = require('./dev/tests/js/jasmine/spec_runner');
runner.init(grunt, { theme: theme });
grunt.task.run(runner.getTasks());
}
}, function (task, name) {
grunt.registerTask(name, task);
});
};
Thanks in advance!

I was getting the same error.
I installed node using the following commands and error resolved.
curl -sL https://deb.nodesource.com/setup_8.x | sudo bash -
sudo apt install nodejs
node -v
npm -v
Hope this helps!

Related

How to configure cypress-sql-server with no cypress.json? (updated)

I'm trying to setup cypress-sql-server, but I'm using version 10.8.0, which does not use cypress.json to configure the environment. All of the setup instructions I've found refer to using cypress.json to configure the plug-in. With the help of u/Fody, I'm closer, but I'm still running into an error:
tasksqlServer:execute, SELECT 'Bob'
CypressError
cy.task('sqlServer:execute') failed with the following error:
The 'task' event has not been registered in the setupNodeEvents method. You must register it before using cy.task()
Fix this in your setupNodeEvents method here:
D:\git\mcare.automation\client\cypress\cypress.config.jsLearn more
node_modules/cypress-sql-server/src/commands/db.js:7:1
5 | }
6 |
> 7 | cy.task('sqlServer:execute', query).then(response => {
| ^
8 | let result = [];
9 |
cypress.config.js
const { defineConfig } = require("cypress");
const sqlServer = require("cypress-sql-server");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// allows db data to be accessed in tests
config.db = {
"userName": "user",
"password": "pass",
"server": "myserver",
"options": {
"database": "mydb",
"encrypt": true,
"rowCollectionOnRequestCompletion": true
}
}
// code from /plugins/index.js
const tasks = sqlServer.loadDBPlugin(config.db);
on('task', tasks);
return config
// implement node event listeners here
},
},
});
testSQL.spec.js
describe('Testing SQL queries', () => {
it("It should return Bob", () => {
cy.sqlServer("SELECT 'Bob'").should('eq', 'Bob');
});
})
My versions:
\cypress> npx cypress --version
Cypress package version: 10.8.0
Cypress binary version: 10.8.0
Electron version: 19.0.8
Bundled Node version:
16.14.2
Suggestions? Is there any more info I can provide to help?
This is the install instruction currently given by cypress-sql-server for Cypress v9
Plugin file
The plug-in can be initialised in your cypress/plugins/index.js file as below.
const sqlServer = require('cypress-sql-server');
module.exports = (on, config) => {
tasks = sqlServer.loadDBPlugin(config.db);
on('task', tasks);
}
Translating that into Cypress v10+
const { defineConfig } = require('cypress')
const sqlServer = require('cypress-sql-server');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// allows db data to be accessed in tests
config.db = {
"userName": "user",
"password": "pass",
"server": "myserver",
"options": {
"database": "mydb",
"encrypt": true,
"rowCollectionOnRequestCompletion": true
}
}
// code from /plugins/index.js
const tasks = sqlServer.loadDBPlugin(config.db);
on('task', tasks);
return config
},
},
})
Other variations work, such as putting the "db": {...} section below the "e2e: {...}" section, but not in the "env": {...} section.
Custom commands
Instructions for Cypress v9
Commands file
The extension provides multiple sets of commands. You can import the ones you need.
Example support/index.js file.
import sqlServer from 'cypress-sql-server';
sqlServer.loadDBCommands();
For Cypress v10+
Just move this code to support/e2e.js
cypress.json is a way to specify Cypress environment variables. Instead of using a cypress.json file, you can use any of the strategies in that link.
If you just wanted to include them in your cypress.config.js, it would look something like this:
const { defineConfig } = require('cypress')
module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:1234',
env: {
db: {
// your db values here
}
}
}
})

Enabling live reload with Grunt on a Vagrant-hosted project

My project uses Vagrant; it's served as https://domain.dev:8443.
The goal is to reload the CSS into the page whenever the CSS changes, without requiring a full page reload.
I am trying to achieve this without any manual action, this means I do not want to use a browser-plugin. Everything should be able to get up and running using the task grunt develop.
grunt-contrib-watch is used to watch 3 different targets, namely css, scss and js. Because these tasks are concurrent, but sadly blocking, I also use grunt-focus to run these 3 tasks at the same time, which correctly works. Whenever changing any file that should be watched, I get a notification in my console that it changed. Awesome.
grunt-contrib-watch recommends connect-livereload, which is middleware for grunt-contrib-connect. This would enable me to get the desired behaviour, but I do not know how to set it up properly.
This is my Gruntfile, note that I did leave out a lot of tasks that are not related to this issue, so it will not run.
module.exports = function(grunt) {
'use strict';
//Load all dependencies that we need
var ConnectLiveReload = require('connect-livereload')();
//Load all packages that we need into Grunt
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-focus');
//The watcher needs a clean object to store data to
var files = Object.create(null);
//Initialize Grunt with the options for all tasks
grunt.initConfig({
connect: {
options: {
port: 0
},
develop: {
options: {
middleware: function(connect) {
return [ConnectLiveReload];
}
}
}
},
focus: {
develop: {}
},
watch: {
scss: {
tasks: ['build'],
files: ['app/webroot/**/*.scss'],
options: {
spawn: false
}
},
css: {
files: ['app/webroot/**/*.css'],
options: {
spawn: false,
livereload: true
}
},
js: {
tasks: ['jasmine:test', 'eslint'],
files: dictionary.javascript,
options: {
spawn: false
}
}
}
});
//Sets the target config for specific tasks 200ms after the last change
var onChange = grunt.util._.debounce(function() {
var target = getTarget();
grunt.config('eslint.target', target);
}, 200);
//Listen to changed files using the watcher
grunt.event.on('watch', function(action, filepath, target) {
files[filepath] = action;
onChange();
});
/**
* Gets the path from the dictionary and adds a JavaScript file selector to it.
*
* #method getPath
* #param [pathkey=webroot]
* #return {String}
*/
function getPath(pathkey) {
pathkey = pathkey || 'webroot';
return (dictionary[pathkey] || pathkey) + '/*.js';
}
/**
* Gets an array of the last-changed files as detected by the watcher.
*
* #method getTarget
* #return {Array}
*/
function getTarget() {
var target = Object.keys(files);
files = Object.create(null);
return target;
}
/**
* #task develop
* #runs watch:css
* #runs watch:scss
* #runs watch:js
*/
grunt.registerTask('develop', 'Start the automated development tasks', function() {
grunt.task.run(['connect:develop', 'focus:develop']);
});
};
http://localhost:35729/livereload.js is a valid file and I can visit in my browser, but the script is not being added to the page. How would I do this?

Grunt bump package.json version

I would like to add 'release' task:
grunt.initConfig({
...
shell: {
release: {
command: function(version) {
return 'git checkout -b release-' + version + ' devel';
}
}
}
...
grunt.loadNpmTasks('grunt-bumpup');
grunt.loadNpmTasks('grunt-shell');
...
grunt.registerTask('release', function() {
grunt.task.run('bumpup');
var version = grunt.config.get('pkg').version;
grunt.task.run('shell:release:' + version);
});
But I have the following:
Running "release" task
Running "bumpup" task
Bumped to: 1.2.5
Running "shell:release:1.2.4" (shell) task
Switched to a new branch 'release-1.2.4'
M Gruntfile.js
M package.json
M src/manifest.json
Done, without errors.
So the version was bumped up, but branch was created for previous version.
I think it is because package.json cached. Can I reread it?
var version = grunt.file.readJSON('package.json').version; // old version too
EDIT:
Adding 'updateProps' to bumpup config will change pkg version property, but:
grunt.registerTask('release', function() {
grunt.task.run('bumpup');
var version = grunt.config.get('pkg').version;
grunt.log.writeln(version); // old version, because tasks run async?
grunt.task.run('shell:release:' + version);
});
Works good:
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
...
bumpup: {
options: {
updateProps: {
pkg: 'package.json'
}
},
files: ['package.json', 'src/manifest.json']
},
shell: {
release: {
command: function() {
return 'git checkout -b release-' + grunt.config.get('pkg').version + ' devel';
}
}
},
...
grunt.loadNpmTasks('grunt-bumpup');
grunt.loadNpmTasks('grunt-shell');
...
grunt.registerTask('release', ['lint', 'bumpup', 'shell:release']);
Are you sure to have set the updateProps option of the grunt-bumpup plugin? This will allow you to specify files to update with the new bumped version after your bumpup task is completed
grunt.initConfig({
...
bumpup: {
options: {
updateProps: {
pkg: 'package.json'
}
},
file: 'package.json'
}
...
});

registerMultiTask.js in grunt-horde

I'm trying to configure grunt-horde so that I can have multiple builds all using a centrally managed task configuration.
The documentation provides the following example of a registerMultiTasks.js file, but I can't get it to work
module.exports = function(grunt) {
var myMultiTask = require('./multi-tasks/secret-sauce.js');
return {
myMultiTask: ['some description', myMultiTask]
};
};
Even if I replace their example with something more simple:
module.exports = function(grunt) {
return {
demo: ['Demo', function() {
console.info('hello');
}]
};
};
When I run grunt demo:test the output is:
Running "demo:test" (demo) task
Verifying property demo.test exists in config...ERROR
>> Unable to process task.
Warning: Required config property "demo.test" missing. Use --force to continue.
Aborted due to warnings.
When I run grunt --help the demo task shows up in the list. Thinking about the warning message I've also tried the following, but again with no luck.
module.exports = function(grunt) {
return {
demo: ['Demo', function(){
return {test: function(){console.info('hello');}};
}]
};
};
...what am I doing wrong?
I figured it out - you need to define the configuration for each target of the multitasks:
initConfig/demo.js
module.exports = function() {
'use strict';
return {
test: {
foo: 'bar'
}
};
};
You can then access this configuration data and the target from within the multitask function:
registerMultiTask.js
module.exports = function(grunt) {
return {
demo: ['Demo', function() {
grunt.log.writeln('target: ' + this.target);
grunt.log.writeln('foo: ' + this.data.foo);
}]
};
};

Conditionally running tasks in grunt if some files are changed

I'm new to Grunt, and from what I understood up till now, Grunt has the "watch" task, which continuously checks files for modifications, and each time modification happens, runs corresponding tasks.
What I'm looking for would be a kind of discrete version of this - a task, that would run other tasks, if and only if some files were changed since the last build.
Seems to be a natural thing to ask for, but I couldn't find this. Is it just me, or is this really an issue?
Configuration file should look like this:
grunt.initConfig({
foo: {
files: "foo/*"
// some task
},
bar: {
files: "bar/*"
// some other task
},
ifModified: {
foo: {
files: "foo/*",
tasks: ['foo']
},
bar: {
files: 'bar/*',
tasks: ['bar', 'foo']
}
}
});
grunt.registerTask('default', ['bar', 'foo']);
Running grunt should always execute tasks 'bar', 'foo', while running grunt ifModified should execute any tasks only if some of the files were actually changed since the previous build.
Made my own task for that. It turned out to be not hard, here is the code:
build/tasks/if-modified.js:
var fs = require('fs');
var crypto = require('crypto');
module.exports = function (grunt) {
grunt.registerMultiTask('if-modified', 'Conditionally running tasks if files are changed.', function () {
var options = this.options({});
grunt.verbose.writeflags(options, 'Options');
var hashes = {};
if (grunt.file.exists(options.hashFile)) {
try {
hashes = grunt.file.readJSON(options.hashFile);
}
catch (err) {
grunt.log.warn(err);
}
}
grunt.verbose.writeflags(hashes, 'Hashes');
var md5 = crypto.createHash('md5');
this.files.forEach(function (f) {
f.src.forEach(function (filepath) {
var stats = fs.statSync(filepath);
md5.update(JSON.stringify({
filepath: filepath,
isFile: stats.isFile(),
size: stats.size,
ctime: stats.ctime,
mtime: stats.mtime
}));
});
});
var hash = md5.digest('hex');
grunt.verbose.writeln('Hash: ' + hash);
if (hash != hashes[this.target]) {
grunt.log.writeln('Something changed, executing tasks: ' + JSON.stringify(options.tasks));
grunt.task.run(options.tasks);
hashes[this.target] = hash;
grunt.file.write(options.hashFile, JSON.stringify(hashes));
}
else
grunt.log.writeln('Nothing changed.');
});
};
Gruntfile.js:
grunt.initConfig({
foo: {
src: ["foo/**/*"],
dest: "foo-dest"
// some task
},
bar: {
src: ["bar/**/*", "foo-dest"]
// some other task
},
'if-modified': {
options: {
hashFile: 'build/hashes.json'
},
foo: {
src: ['foo/**/*', 'Gruntfile.js', 'package.json'],
options: {tasks: ['foo']}
},
bar: {
src: ['bar/**/*', "foo-dest", 'Gruntfile.js', 'package.json'],
options: {tasks: ['bar']}
}
}
});
grunt.loadTasks('build/tasks'); // if-modified.js in this dir
grunt.registerTask('default', ['foo', 'bar']);
run:
grunt if-modified
You could create a task that runs conditionally other tasks, from https://github.com/gruntjs/grunt/wiki/Creating-tasks :
grunt.registerTask('foo', 'My "foo" task.', function() {
// Enqueue "bar" and "baz" tasks, to run after "foo" finishes, in-order.
grunt.task.run('bar', 'baz');
// Or:
grunt.task.run(['bar', 'baz']);
});
What you need might be grunt-newer :
The newer task will configure another task to run with src files that are a) newer than the dest files or b) newer than the last successful run (if there are no dest files). See below for examples and more detail.
https://github.com/tschaub/grunt-newer

Resources