How to create a gulp file with reusable functions - Multiple Watch points & Multiple Output destinations - gulp-watch

Goal is to use this Gulp file to execute 'n' number of different source & destinations.
How can we pass the arguments(source, destination) so that the CSS-Generator task is accepting those source & destinations and giving out the separate output files.
var gulp = require("gulp"),
sass = require("gulp-sass"),
postcss = require("gulp-postcss"),
autoprefixer = require("autoprefixer"),
cssnano = require("cssnano");
var paths = {
styles: {
src1: "scss/slider-one/index.scss",
src2: "scss/slider-two/index.scss"
dest1: "slider-one",
dest2: "slider-two"
}
};
function style1() {
return (
gulp
.src(paths.styles.src1)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(paths.styles.dest1))
);
}
exports.style1 = style1;
function style2() {
return (
gulp
.src(paths.styles.src2)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(paths.styles.dest2))
);
}
exports.style2 = style2;
function watch() {
style1();
style2();
gulp.watch("scss/slider-one/*.scss", style1);
gulp.watch("scss/slider-two/*.scss", style2);
}
exports.watch = watch

Your source is scss/slider-one/index.scss & destination is slider-one and watch is scss/slider-one/*.scss.
slider-one is common in source, destination & watch.
So you can define the paths array as ["slider-one","slider-two"]
And you are calling the style1 & style2 as the callback of watch function. So you can club that and define that in one function.
And call that function inside for loop with parameters (source,destination,watch).
Full Code:
var gulp = require("gulp"),
sass = require("gulp-sass"),
postcss = require("gulp-postcss"),
autoprefixer = require("autoprefixer"),
cssnano = require("cssnano");
function runGulpSass(src,dest,watch) {
gulp.watch(watch, function() {
return gulp.src(src)
.pipe(sass())
.on("error", sass.logError)
.pipe(postcss([autoprefixer(), cssnano()]))
.pipe(gulp.dest(dest))
});
}
exports.runGulpSass = runGulpSass;
function startGulp() {
var paths = ["slider-one","slider-two"];
for(var i=0;i<paths.length;i++) {
runGulpSass("scss/"+paths[i]+"/index.scss",paths[i],"scss/"+paths[i]+"/*.scss")
}
}
exports.watch = startGulp
[Edit] If there is no common value in source, destination & watch :
Define the paths array like this :
var paths = [
["scss/slider-one/index.scss","css/slider-one","slider-one/*.scss"],
["scss/slider-two/index.scss","css/slider-two","slider-two/*.scss"]
];
And set the runGulpSass function parameter like this :
runGulpSass(paths[i][0],paths[i][1],paths[i][2])

Related

How to use custom style loader in Vite

We have a react project and using webpack for bundling but also we want to try vite too. Webpack bundle css files from style-loader.js too. In style-loader.js we have some rules which are related to components and components are added to node modules. My rule's aim is mainly importing css files from node_modules components. When we run our project with vite, Our custom scss files does not override css which came from components. Is there any solution for override or Is there any way to use a custom style loader in vite ?
Our custom style loader webpack-dev is;
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: './config/webpack/style-loader'
},
]}
Our style-loader.js file is;
const babylon = require('babylon');
const traverse = require('babel-traverse').default;
const fs = require('fs');
module.exports = function (source) {
var astResult = babylon.parse(source, {
sourceType: "module",
ranges: true,
plugins: [
"jsx",
"objectRestSpread",
"flow",
"typescript",
"decorators",
"doExpressions",
"classProperties",
"classPrivateProperties",
"classPrivateMethods",
"exportExtensions",
"asyncGenerators",
"functionBind",
"functionSent",
"dynamicImport",
"numericSeparator",
"optionalChaining",
"importMeta",
"bigInt",
"optionalCatchBinding"
]
});
let addedIndexCounter = 0;
let isViewDirty = false;
traverse(astResult, {
enter: function (path) {
let node = path.node;
if (node.type == 'ImportDeclaration' &&
node.source &&
node.source.type == 'StringLiteral' &&
node.source.value &&
node.source.value.indexOf('#packagename') >= 0 &&
node.source.value.indexOf('core') < 0 &&
node.source.value.indexOf('.css') < 0) {
if(fs.existsSync('./node_modules/' + node.source.value + '/styles.css')) {
let starting = node.end;
starting += addedIndexCounter;
let targettacCss = "; import '" + node.source.value + "/styles.css';"
addedIndexCounter += targettacCss.length;
source = source.substring(0, starting) + targettacCss + source.substring(starting);
isViewDirty = true;
}
}
}
});
/*if(isViewDirty){
let fileName = "view_" + (new Date()).toISOString().slice(0, 10)+"_" + Math.random().toString(35).substr(2,10);
fs.writeFileSync('./logs/views/' + fileName, source);
}*/
return source;
};
You can use plugins to achieve your feature, the following is my general idea.
// vite.config.js
import { defineConfig } from "vite";
import customerPlugin from "./plugin/customer-plugin";
export default defineConfig(() => {
return {
// ..
plugins: [customerPlugin()] // Put your plugin here
};
});
// ./plugin/customer-plugin.js
const customerPlugin = () => {
return {
name: "customer-transform",
transform(code, id) {
// id = "/some/path/xxx.js"
if (!id.endsWith(".js")) return; // Only transform js file.
let resultCode = "";
// Paste your transform logic here.
return resultCode;
}
};
};
export default customerPlugin;
reference: https://vitejs.dev/guide/api-plugin.html

vscode findFiles returns nothing but npm glob returns correct results

I'm writing and vscode extension in which I need a list of the test files inside workspace.
To find the test files I'm using the default testMatch from the jest.config.js which is:
[
'**/__tests__/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[jt]s?(x)'
]
My problem is that vscode.workspace.findFiles returns empty array and I cannot set it up to get correct results, but using Glob package the output is correct.
protected async findTestFiles(
matchTestsGlobPatterns: string[]
): Promise<vscode.Uri[]> {
const testFilesUris: vscode.Uri[] = [];
const glob_testFilesUris: vscode.Uri[] = [];
const { name: workspaceName, workspaceFolders } = vscode.workspace;
if (workspaceName === undefined || workspaceFolders === undefined) {
throw new Error(`No active workspace${!workspaceFolders ? ' folders' : ''}.`);
}
for (let folderIdx = 0; folderIdx < workspaceFolders.length; folderIdx++) {
const folder = workspaceFolders[folderIdx];
// - by vscode.workspace.findFiles
for (let patternIdx = 0; patternIdx < matchTestsGlobPatterns.length; patternIdx++) {
const currentPattern = matchTestsGlobPatterns[patternIdx];
const pattern = new vscode.RelativePattern(
folder.uri.fsPath,
currentPattern
);
const files = await vscode.workspace.findFiles(
pattern,
'**/node_modules/**'
);
testFilesUris.push(...files);
}
console.log('by [vscode.workspace.findFiles]', testFilesUris.length);
// - by npm Glob
var glob = require('glob');
for (let patternIdx = 0; patternIdx < matchTestsGlobPatterns.length; patternIdx++) {
const currentPattern = matchTestsGlobPatterns[patternIdx];
const files: any[] = await new Promise((resolve, reject) => {
glob(
currentPattern,
{
absolute: true,
cwd: folder.uri.fsPath,
ignore: ['**/node_modules/**']
},
function (err: Error, files: any[]) {
if (err) {
return reject(err);
}
resolve(files);
}
);
});
glob_testFilesUris.push(...files);
}
console.log('by [npm Glob]', glob_testFilesUris.length);
}
// #todo: remove duplicates.
return testFilesUris;
}
The example console output of this function for some project is:
by [vscode.workspace.findFiles] 0
by [npm Glob] 45
Project structure:
rootFolder
src
__tests__
files.test.ts
...
utils
array.test.ts
...
So my question is how do I call vscode.workspace.findFiles to get correct results, or is there known problem with this function?
I have found some kind of answer to the question.
The problem is ?(x) in patterns. The vscode.workspace.findFiles does not work with this pattern as other packages do. If remove it from mentioned glob patterns they work except the .jsx | .tsx files are ommited.
After deep dive into vscode github's issues I have learned (here) that vscode.workspace.findFiles does not support extended patterns like ?(patterLike)

Gulp-eslint throws errors on dynamically loaded JSs

I have a project structure like
There are approx 10 JS files in com. lab1 and lab2 has a config.json file which tells, out of 10 files which files to be concatenated and placed as app-min.js in dist/lab1 or dist/lab2.
In the gulp file I've created something like this.
var filesArr = [];
var labName;
// Player Task
gulp.task('player', function () {
return gulp.src(filesArr)
.pipe(eslint())
.pipe(babel())
.pipe(concat('app-min.js'))
.pipe(uglify({
compress: {
drop_console: true
}
}).on('error', gutil.log))
.pipe(gulp.dest('dist/' + labName));
});
// Clean
gulp.task('clean', function () {
if (readJson()) {
return del([
'dist/' + labName
]);
}
return null;
});
// Watch
gulp.task('watch', function () {
gulp.watch(filesArr, gulp.series('player'));
});
// Read Json and create JS Array
function readJson() {
// LAB STRUCTURE
var _n = prompt('Specify the LAB name. ');
labName = _n;
var _path = path.resolve('./src/' + _n);
var _exists = fs.existsSync(_path);
if (_exists) {
var _json = fs.readFileSync(path.resolve(_path + '/labstructure.json'), 'utf-8');
var _jObj = JSON.parse(_json).labObj.components;
for (var i = 0; i < _jObj.length; i++) {
var _jsName = 'src/com/component/' + _jObj[i].ref + '.js';
if (filesArr.indexOf(_jsName) === -1) {
filesArr.push(_jsName);
}
}
}
return _exists;
}
gulp.task('default', gulp.series('clean', 'player', 'watch'));
Here the filesArr looks like:
[ 'src/com/component/ColorActClass.js',
'src/com/component/PanelCompClass.js',
'src/com/component/ToggleCompClass.js',
'src/com/component/SliderCompClass.js',
'src/com/component/CheckBoxCompClass.js',
'src/com/component/ButtonCompClass.js',
'src/com/component/LabelCompClass.js',
'src/com/component/InputBoxClass.js',
'src/com/component/ColorMonitorClass.js',
'src/com/component/MsgBoxClass.js',
'src/com/component/ConfBoxClass.js',
'src/com/component/NumberPadClass.js',
'src/com/main/lib/webfontloader.js',
'src/com/main/lib/howler.core.min.js',
'src/com/main/PlayerClass.js',
'src/kl1001_color/BrainClass.js' ]
This works perfectly fine at the first place. But when any JS is modified then in watch player task throws eslint error on some files which are untouched. This doesn't happen always rather if watch is running for 10-20 mins then it throws error. Like this:
In this case CheckBoxCompClass.js is not the file which is modified, but still got the issue. On top of that, the semicolon is in place. If this file has issue then eslint should have thrown the error at the first place.
Please help.
Accidentally, my NVM was set to an older version. Solved the issue after updating the NVM and by setting the current NVM version to the latest one.

Dynamic import in different folder

I have some trouble to import dynamicaly a class.
I use alias for this projet :
config.resolve.alias = {
App: path.resolve('./src/'),
Reactive: path.resolve('./app/')
}
I want to import a list of class :
const classes = {
foo: 'App/Foo',
bar: 'App/Bar'
};
let list = {};
for(var c in classes) {
(async (k, v, list) => {
const m = await import(`${v}`);
list[k] = new m.default();
})(c, classes[c], list);
}
This script is called in app, and all imported classes in src.
The error is simple : Cannot find module 'App/Foo'.
When I check the last entry of error's log :
var map = {
"./OtherClass1": [
"./app/OtherClass1.js"
],
"./OtherClass1.js": [
"./app/OtherClass1.js"
],
"./OtherClass2": [
"./app/OtherClass2.js"
],
"./OtherClass2.js": [
"./app/OtherClass2.js"
]
};
function webpackAsyncContext(req) {
var ids = map[req];
if(!ids)
return Promise.reject(new Error("Cannot find module '" + req + "'."));
return Promise.all(ids.slice(1).map(__webpack_require__.e)).then(function() {
return __webpack_require__(ids[0]);
});
};
webpackAsyncContext.keys = function webpackAsyncContextKeys() {
return Object.keys(map);
};
webpackAsyncContext.id = "./app lazy recursive ^.*$";
module.exports = webpackAsyncContext;
So, the error is legit, because the map does not contain Foo and Bar classes in src, only those in app.
How can I specify to Webpack to check in both folders, recursively?
But, when I test this, it's work fine :
for(var c in classes) {
(async (k, v, list) => {
const m = await import(`${"App/Foo"}`);
list[k] = new m.default();
})(c, classes[c], list);
}
use react import to import your file and use file.classname to call them
eg import claases from '/src';
and use it link
app = classes.myfile

React Native packager isn't including a 3rd party library in the bundle

What's the best way to debug the react-native packager not including a dependency in the output bundle? What I have:
Module is included in package.json and appears in my node_modules
I'm using typescript, and the compiled js file has the require('countdown') line.
If I inspect the output bundle, or log the var countdown = require('countdown'), I can see that the source for countdown.js isn't included in the bundle.
If I use webpack to create a web bundle, it works as expected.
Here's the compiled js code which is having issues:
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var RX = require("reactxp");
var countdown = require("countdown");
var styles = {
outerContainer: RX.Styles.createViewStyle({
flexDirection: "row"
}),
innerContainer: RX.Styles.createViewStyle({
flexDirection: "column",
alignItems: "center",
paddingHorizontal: 5
})
};
var CountdownTimer = (function (_super) {
__extends(CountdownTimer, _super);
function CountdownTimer() {
var _this = _super.call(this) || this;
_this._setStateToNow = function () {
_this.setState({ currentDate: new Date(Date.now()) });
};
_this.state = { currentDate: new Date() };
return _this;
}
CountdownTimer.prototype.componentDidMount = function () {
this.timerId = setInterval(this._setStateToNow, 1000);
};
CountdownTimer.prototype.componentWillUnmount = function () {
clearInterval(this.timerId);
};
CountdownTimer.prototype.render = function () {
// THIS LINE FAILS SINCE 'countdown' is {}
var diff = countdown(this.state.currentDate, this.props.untilDate, CountdownTimer.DIFF_ARGS);
....
};
CountdownTimer.DIFF_ARGS = countdown.DAYS |
countdown.HOURS |
countdown.MINUTES |
countdown.SECONDS;
return CountdownTimer;
}(RX.Component));
exports.CountdownTimer = CountdownTimer;
The error I'm getting is Object is not a function, and logging the var countdown shows it is {}, and inspecting the index.android.bundle shows that the source code for countdown.js isn't included.
I am running the packager with node ./node_modules/react-native/local-cli/cli.js start

Resources