Warning: connect.static is not a function Use --force to continue - gruntjs

I am using YO lessapp project, "grunt-contrib-connect" helps me to start a node js server on 9000 port. Whenever I run grunt serve (start the server) the service is aborted due to the below warning.
Running "connect:livereload" (connect) task
Warning: connect.static is not a function Use --force to continue.
The exact error took place in the below function in Gruntfile.js
livereload: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
I have installed
npm install grunt-contrib-connect --save-dev,
npm install serve-static --save-dev
I came across few post, some suggest to turn off the firewall but no luck.
I know there is something to do with my machine or npm/node/connect version conflicts, because I tried to run the same app from other machine and it works fine.
System configuration :
Windows 7 Professional
Node -v4.1.2
npm -v2.14.4
connect#3.4.0
I have installed connect and serve-static based upon the post nodejs connect cannot find static, but still the same
Any help? Thanks in Advance

You have to install connect and serve-static:
npm install --save-dev grunt-contrib-connect serve-static
And then you have to import serve-static in Gruntfile.js:
module.exports = function (grunt) {
...
var serveStatic = require('serve-static');
grunt.initConfig({
...
connect: {
...
livereload: {
options: {
middleware: function(connect) {
return [
serveStatic('.tmp'),
connect().use('/bower_components', serveStatic('./bower_components')),
serveStatic(config.app)
];
}
}
}

From version 0.11.x, the new grunt-contrib-connect does not support connect.static and connect.directory.
You should install serve-static(for serve static files) and serve-index (for Serves pages that contain directory listings for a given path).
like this:
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
Use serveStatic instead connect.static
and
serveIndex instead connect.directory
grunt.initConfig({
connect: {
options: {
test: {
directory: 'somePath',
middleware: function(connect, options){
var _staticPath = path.resolve(options.directory);
return [serveStatic(_staticPath), serveIndex(_staticPath)]
}
}
}
}
})

Related

How do you shim react-pdf with esbuild?

If you bundle react-pdf for the browser using esbuild today you will run into errors that prompt you to build for platform=node because zlib and stream are not available in the browser environment.
I did find a conversation around how to swap this when using vite but I'm curious if others have created a shim for esbuild that offers something equivalent
process: "process/browser",
stream: "vite-compatible-readable-stream",
zlib: "browserify-zlib"
the version I'm using today: #react-pdf/renderer": "^2.0.21"
edit
It just so happens a node modules polyfill exists for esbuild and you should be able to configure this as a plugin
https://github.com/remorses/esbuild-plugins#readme
npm i -D #esbuild-plugins/node-globals-polyfill
and then w/ esbuild you can pass it in like so
https://esbuild.github.io/plugins/#using-plugins
More after I confirm this is working end to end
I was able to achieve this using esbuild v0.14.10 and 2 plugins
npm i -D #esbuild-plugins/node-modules-polyfill
npm i -D #esbuild-plugins/node-globals-polyfill
With a build configuration like this
const esbuild = require('esbuild')
const globalsPlugin = require('#esbuild-plugins/node-globals-polyfill')
const modulesPlugin = require('#esbuild-plugins/node-modules-polyfill')
const args = process.argv.slice(2)
const deploy = args.includes('--deploy')
const loader = {
// Add loaders for images/fonts/etc, e.g. { '.svg': 'file' }
}
const plugins = [
globalsPlugin.NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
define: { 'process.env.NODE_ENV': deploy ? '"production"' : '"development"' },
}),
modulesPlugin.NodeModulesPolyfillPlugin(),
]
let opts = {
entryPoints: ['js/app.js'],
bundle: true,
target: 'es2017',
outdir: '../priv/static/assets',
logLevel: 'info',
inject: ['./react-shim.js'],
loader,
plugins
}
if (deploy) {
opts = {
...opts,
minify: true
}
}
const promise = esbuild.build(opts)

How to use TS Path Mapping with Firebase Cloud Functions

How do I use TS Path Mapping with Firebase Cloud Functions?
I tried without success:
"baseUrl": ".",
"paths": {
"#custom-path/*": ["src/utils/*"],
"#other-path/*": ["../other/path/*"]
}
Finally I was able to do this with module-alias NPM package.
Install it as non-dev dependency: yarn add module-alias #types/module-alias
Create a file fixTsPaths.ts or whatever with content like this:
import * as ModuleAlias from 'module-alias';
ModuleAlias.addAliases({
'common': __dirname + '/../../../common',
});
Here's the trick about the path /../../../common: in my case this folder is outside functions, and Typescript replicates folders structure during the build, so that's could be the reason why https://github.com/dividab/tsconfig-paths was not working out of the box. So in every case one needs to check this path and find appropriate '..' count :)
And finally import this file in your index.ts at the very top:
import './fixTsPaths';
Hope this helps!
It's 2022 and the neatest way to do this is to use tsc-alias.
On tsconfig.json, add baseUrl and add your paths under compilerOptions. Something like:
{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"#constants/*": ["api/constants/*"],
"#interfaces/*": ["api/interfaces/*"],
"#middlewares/*": ["api/middlewares/*"],
"#modules/*": ["api/modules/*"],
"#services/*": ["api/services/*"]
},
...
}
Then, change your serve and build scripts, under package.json. Like:
...
"scripts": {
"build": "tsc && tsc-alias",
"build:watch": "concurrently \"tsc -w\" \"tsc-alias -w\"",
"serve": "concurrently --kill-others \"firebase emulators:start --only functions\" \"npm run build:watch\"",
...
},
...
☝️ here I'm using concurrently, but feel free to use whatever you like.
And that's it. You can now import stuff using your defined paths, like:
import { messages } from '#constants/responses'
import CandidatesService from '#modules/candidates/candidates.service'
import { IModule } from '#interfaces/module.interface'
etc...
The problem is the rule no-implicit-dependencies: true on the tslint.json. You can pass additional params to whitelist your custom paths:
"no-implicit-dependencies": [true, ["#custom-path", "#other-path"]],
for anyone who still struggles with this issue, but the below code at the top of the entry point file (main.ts).
don't forget to adjust the tsconfig.json file path if it is not in the default location
const tsConfig = require('../tsconfig.json');
const tsConfigPaths = require('tsconfig-paths');
tsConfigPaths.register({
baseUrl: __dirname,
paths: tsConfig.compilerOptions.paths,
});
I was able to do this with #zerollup/ts-transform-paths NPM package.
Install #zerollup/ts-transform-paths as dev dependency: yarn add -D #zerollup/ts-transform-paths
Setup following config of webpack + ts-loader.
const tsTransformPaths = require('#zerollup/ts-transform-paths');
module.exports = {
... // other config
module: {
rules: [
{
test: /\.(ts|tsx)$/,
loader: 'ts-loader',
options: {
getCustomTransformers: (program) => {
const transformer = tsTransformPaths(program);
return {
before: [transformer.before], // for updating paths in generated code
afterDeclarations: [transformer.afterDeclarations] // for updating paths in declaration files
};
}
}
}
]
}
};
See more in detail: https://github.com/zerkalica/zerollup/tree/5aee60287647350215c81d0b2da5a30717d9dccb/packages/ts-transform-paths

load-grunt-config cannot read my custom config and call copy task from Gruntfile.js instead from my custom copy.js file

I'm trying to override copy task using load-grunt-config.
In my Gruntfile.js I have copy task that I want to override by custom copy task.
In Gruntfile.js also I have this configuration for load-grunt-config:
require('load-grunt-config')(grunt, {
configPath: path.join(process.cwd(), 'grunt/config'),
jitGrunt: {
customTasksDir: 'grunt/tasks'
}
});
This is grunt/config/copy.js content:
module.exports = {
main: {
src: 'test/*',
dest: 'copyTest'
};
And here is grunt/tasks/default.js content:
module.exports = function (grunt) {
grunt.registerTask('default', ['copy:main']);
};
When I run the default task I got error:
Loading "copy.js" tasks...OK
+ copy
Running "copy:main" (copy) task
Verifying property copy.main exists in config...ERROR
>> Unable to process task.
Warning: Required config property "copy.main" missing. Use --force to continue.
Aborted due to warnings.
Any idea what could be wrong?

Auto Starting Protractor Runner

I have a Grunt task called "test". The responsibility of this task is the execute end-to-end tests. Currently, I can run my tests if I start the grunt-protractor-runner in a seperate command-line window. I start that by executing the following command:
node_modules\grunt-protractor-runner\node_modules\protractor\bin\webdriver-manager start
My question is, is there a way I can start this as part of my grunt task if the webdriver-manager hasn't already been started? If so, how? I've seen tasks like grunt-contrib-connect, yet I don't see how those allow me to get my test server running as part of a task.
protractor will take care of starting the selenium server for you if you don't define seleniumAddress in the protractor config file.
It seems like you're pretty much there. Your 'test' task should first start up a server using grunt-contrib-connect to serve the app you want to test. That task should then use grunt-protractor-runner to start protractor and protractor will start the selenium server (assuming seleniumAddress=null).
Something like the following:
connect: {
test: {
options: {
port: 9001,
base: [
'app'
]
}
}
}
protractor: {
options: {
keepAlive: true,
configFile: 'protractor.conf.js'
},
run: {}
}
grunt.registerTask('test', [
'connect:test',
'protractor:run'
]);
To start webdriver automatically put following in your grunt file:
grunt.initConfig: ({
..
protractor: {
test: {
options: {
configFile: 'protractor.conf.js'
}
}
},
..
}
..
grunt.registerTask('test': ['protractor:test']);
and following in your ./protractor.conf.js
var chromeDriver =
'./node_modules/protractor/selenium/chromeDriver';
var platform = require('os').platform();
var fs = require('fs');
var platformChrome = chromeDriver + '-' + platform;
if (fs.existsSync(platformChrome)){
log.console('Using ' + platform + ' specific driver ');
chromeDriver = platformChrome;
}
exports.config = {
directConnect: true,
chromeDriver: chromeDriver,
// Capabilities to be passed to the webdriver instance
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
args: ['--no-sandbox']
}
},
..
}
Start your grunt server:
grunt serve;
and in another terminal start your tests:
grunt test

grunt less task fails silently when not using grunt-cli

I am at a loss as to why the less task fails silently. If I run it using grunt-cli and Gruntfile.js it works fine, but when I try to port it into another script the less task does not generate any output. Any help or insight as to why would be greatly appreciated.
'use strict';
var grunt = require('grunt'),
_ = require('underscore'),
path = require('path'),
fs = require('fs'),
dir = require('node-dir');
var cssSrc = [];
var cssPaths = [];
var templates = [];
dir.paths('repo', function (err, paths) {
if (err) {
throw err;
}
_.each(paths.files, function (file) {
if (path.extname(file) === '.less') {
cssSrc.push(file);
}
});
cssPaths = paths.dirs;
grunt.task.loadNpmTasks('grunt-contrib-less');
grunt.initConfig({
less: {
options: {
paths: cssPaths
},
files: {
'tmp/target.css': cssSrc
}
}
});
grunt.task.run('less');
});
The dependencies implicit to grunt-cli:
nopt
findup-sync
resolve
are not explicitly included in a standalone script.
The Gruntfile.js script contains the path information:
repo paths found using the dir.paths callback
tmp/target.css paths found using _.each
.less source paths found using paths.dirs
and uses the dependencies to do pathfinding.
There are unrelated questions about running less via Rhino and wsh which explain the parameters for doing path finding explicitly.
References
npm: less
npm: grunt-cli
npm scripts man page
grunt-cli source
less: Third Party Compilers

Resources