How to copy multiple files and keep the folder structure with Gulp - javascript

I am trying to copy files from one folder to another folder using Gulp:
gulp.task('move-css',function(){
return gulp.src([
'./source/css/one.css',
'./source/other/css/two.css'
]).pipe(gulp.dest('./public/assets/css/'));
});
The above code is copying one.css & two.css to the public/assets/css folder.
And if I use gulp.src('./source/css/*.css') it will copy all CSS files to the public/assets/css folder which is not what I want.
How do I select multiple files and keep the folder structure?

To achieve this please specify base.
¶ base - Specify the folder relative to the cwd. Default is where the glob begins. This is used to determine the file names when saving in .dest()
In your case it would be:
gulp.task('move-css',function(){
return gulp.src([
'./source/css/one.css',
'./source/other/css/two.css'
], {base: './source/'})
.pipe(gulp.dest('./public/assets/'));
});
Folder structure:
.
├── gulpfile.js
├── source
│ ├── css
│ └── other
│ └── css
└── public
└── assets

I use gulp-flatten and use this configuration:
var gulp = require('gulp'),
gulpFlatten = require('gulp-flatten');
var routeSources = {
dist: './public/',
app: './app/',
html_views: {
path: 'app/views/**/*.*',
dist: 'public/views/'
}
};
gulp.task('copy-html-views', task_Copy_html_views);
function task_Copy_html_views() {
return gulp.src([routeSources.html_views.path])
.pipe(gulpFlatten({ includeParents: 1 }))
.pipe(gulp.dest(routeSources.html_views.dist));
}
And there you can see the documentation about gulp-flatten: Link

gulp.task('move-css',function(){
return gulp
.src([ 'source/**'], { base: './' })
.pipe(gulp.dest('./public/assets/css/'));
});
Your own code didn't include the entire dir tree of source 'source/**' and the base {base:'./'} when calling to gulp.src which caused the function to fail.
The other parts where fine.
gulp.task('move-css',function(){
return gulp.src([
'./source/css/one.css',
'./source/other/css/two.css'
]).pipe(gulp.dest('./public/assets/css/'));
});

Related

Allow imports only from index file of folder, except inside the folder with import/no-internal-modules

Given the following folder structure:
my-project
├── components
│ └── getUser.js
│ └── updateUser.js
└── utils
└── models
│ └──index.ts
│ └──api.ts
└── services
└──index.ts
└──api.ts
└──price
└──index.ts
└──getPrice.ts
I would like to make sure that every filt outside of the services folder only imports from the service index file, like so:
import { getPrice } from 'utils/services';
but I would also like files inside the services folder to import from each other, for example that the api file can do import { getPrice } from './price';
I have this rule in the root .eslintrc
"import/no-internal-modules": [ "error", {
"forbid": [ "/**/util/services/*" ]
} ]
and inside the services folder I have another .eslintrc with this rule:
"import/no-internal-modules": [
"error",
{
"allow": [
"util/services/**"
]
}
]
But running this seems to do the exact opposite of what I want, right now it only gives error for all the files in the services folder, saying for example Reaching to "./price/get" is not allowed on a file inside the services folder.

Grunt cssmin and timestamp filename

I'm trying to set up a grunt task that outputs a minified css file and changes the file name with a timestamp.
My Gruntfile looks like this:
module.exports = function (grunt) {
//project configurations
grunt.initConfig({
cssmin: {
target: {
src: ["css/aw2018.css", ],
dest: "dist/aw2018.min.css"
}
}
replace: {
foo: {
options: {
variables: {
'timestamp': '<%= new Date().getTime() %>'
},
force: true
},
files: [{
expand: true,
cwd: 'css/',
src: ['*.css/*.js'],
dest: 'dist/',
ext: '.<%= new Date().getTime() %>.js'
}]
}
}
});
//load cssmin plugin
grunt.loadNpmTasks('grunt-contrib-cssmin');
//create default task
grunt.registerTask("default", ["cssmin"]);
grunt.registerTask('default', 'replace');
};
But I get an error of
Loading "Gruntfile.js" tasks...ERROR
SyntaxError: Unexpected identifier
Warning: Task "default" not found. Use --force to continue.
EDIT:
This is what I'm ultimately trying to achieve:
Minify a css file
Add a timestamp to the end of the file name.
I would like to have it work for any css file in a folder but keep them separate. For instance, lets say I have aw2018.css and aw2017.css. I would like both of them to run through the task and then be output to their own individual minified css file with the timestamp of YYYY-MM-DD-HH-MM-SS at the end of the filename.
This can be achieved by utilizing grunt's rename function when building the files object dynamically, instead of using another task.
The documentation describes grunts rename function as follows:
rename Embeds a customized function, which returns a string containing the new destination and filename. This function is called for each matched src file (after extension renaming and flattening).
Inside the body of the rename function is where you add your custom logic to append a timestamp to each filename.
The following Gruntfile.js configuration shows how to achieve this:
Gruntfile.js
module.exports = function (grunt) {
var path = require('path'); // Load nodes built-in `path` module.
// Obtain local timestamp formatted as: YYYY-MM-DD-HH-MM-SS
var tzOffset = (new Date()).getTimezoneOffset() * 60000;
var timeStamp = (new Date(Date.now() - tzOffset)).toISOString().slice(0, -1)
.replace(/\.[\w\W]+?$/, '') // Delete from dot to end.
.replace(/\:|\s|T/g, '-'); // Replace colons, spaces, and T with hyphen.
grunt.initConfig({
cssmin: {
timestamp: {
files: [{
expand: true,
cwd: 'css/',
src: ['aw2017.css', 'aw2018.css'],
dest: 'dist/',
/**
* Grunt rename function generates new destination filepath,
# adds timestamp, and new min.css extension to the file name.
# (https://gruntjs.com/configuring-tasks#the-rename-property)
#
* #param {String} dest - The path to the desination directory.
* #param {String} src - The path to the source directory.
* #returns {String} New dest path with time-stamped filename.
*/
rename: function(dest, src) {
var fileExt = path.extname(src),
fileName = path.basename(src, fileExt),
dirName = path.dirname(src),
newFileExt = ['.min', fileExt].join(''),
newFileName = [fileName, '-', timeStamp, newFileExt].join(''),
newDestPath = path.join(dest, dirName, newFileName);
return newDestPath;
}
}]
}
}
});
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask('default', ['cssmin:timestamp']);
};
Additional info:
Firstly, in the Gruntfile.js above, we load the nodejs built-in path module via the line reading.
var path = require('path');
This module is used later in the rename function to help create the new time-stamped filename, and ascertain the destination filepath to be return'ed:
We then create a local timestamp formatted as YYYY-MM-DD-HH-MM-SS via the lines reading:
var tzOffset = (new Date()).getTimezoneOffset() * 60000;
var timeStamp = (new Date(Date.now() - tzOffset)).toISOString().slice(0, -1)
.replace(/\.[\w\W]+?$/, '') // Delete from dot to end.
.replace(/\:|\s|T/g, '-'); // Replace colons, spaces, and T with hyphen.
Note: We assign the generated timestamp to the timeStamp variable outside of any grunt task(s) to ensure all resultant filenames get the same timestamp.
The date/time format will be based on your local timezone and not UTC (Coordinated Universal Time).
We then reconfigure your cssmin task to build the files object dynamically instead of utilizing the compact format. By configuring the task this way we get access to the rename function.
Further usage and modifications to the current config:
The Gruntfile.js configuration provided above takes a two source CSS files, named aw2017.css and aw2018.css from the following directory structure:
.
└── css
├── aw2017.css
└── aw2018.css
After running the grunt command via your CLI, it outputs both minified (time-stamped) .css files to the new dist directory. Resulting as this:
.
├── css
│ ├── aw2017.css
│ └── aw2018.css
└── dist
├── aw2017-2018-05-09-08-35-57.min.css
└── aw2018-2018-05-09-08-35-57.min.css
However, if you want to also include the source css folder in the dist directory like this:
.
├── css
│ ├── aw2017.css
│ └── aw2018.css
└── dist
└── css
├── aw2017-2018-05-09-08-35-57.min.css
└── aw2018-2018-05-09-08-35-57.min.css
then you need to change the values of the cwd and src properties in the cssmin task to this:
// ...
cwd: '.',
src: ['css/aw2017.css', 'css/aw2018.css'],
// ...
Minifying and time-stamping multiple .css files using a glob pattern
Currently, in your question, you seem to only want to minify two .css file, namely aw2017.css and aw2018.css.
However, if you wanted to minify (and time-stamp) many .css files found in the css directory, however many levels deep, you can utilize a globbing pattern. For example, lets say your source css directory looks like this:
.
└── css
├── a.css
├── b.css
├── foo
│ ├── bar
│ │ └── c.css
│ └── d.css
└── quux
└── e.css
...and if you change the values of the cwd and src properties in your cssmin task to this:
// ...
cwd: '.',
src: ['css/**/*.css'],
// ...
Your resultant output will be something like this:
.
├── css
│ └── ...
└── dist
└── css
├── a-2018-05-09-08-35-57.min.css
├── b-2018-05-09-08-35-57.min.css
├── foo
│ ├── bar
│ │ └── c-2018-05-09-08-35-57.min.css
│ └── d-2018-05-09-08-35-57.min.css
└── quux
└── e-2018-05-09-08-35-57.min.css

Unable to require() from inside an already "required" module

I have this project structure:
myApp
├── gulpfile.js
├── package.json
└── source
   └── scripts
      ├── modules
      │ └── utils.js
      ├── background.js
      └── data.json
My browserify task:
gulp.task('browserify', function () {
return gulp.src(['./source/scripts/**/*.js'])
.pipe($.browserify({
debug: true,//for source maps
standalone: pkg['export-symbol']
}))
.on('error', function(err){
console.log(err.message);
this.emit('end');
})
.pipe(gulp.dest('./build/scripts/'));
});
My sample utils.js:
const data = require('../data.json');
const utils = (function () {
const output = function () {
console.log(data);
};
return {
output: output,
};
}());
module.exports = utils;
If I try to build it with the current directory structure, I get this error:
module "../data.json" not found from "/dev/myApp/source/scripts/fake_4d8cf8a4.js"
I can only build it, if I put data.json inside the modules directory AND inside the scripts directory, ie. it only works if I duplicate the file:
myApp
├── gulpfile.js
├── package.json
└── source
   └── scripts
      ├── modules
      │ ├── utils.js
      │ └── data.json
      ├── background.js
      └── data.json
Obviously this is not okay... what am I doing wrong?
Thank you
I'm inferring from your use of gulp.src to pass files to $.browerify that you are using a Gulp plugin, probably gulp-browserify. It is generally not recommended to use a plugin to invoke Browserify from Gulp. The recommended way to do it is to just call Browserify directly. Indeed, Gulp's blacklist of plugins states:
"gulp-browserify": "use the browserify module directly",
I've replicated your directory structure and put some reasonable values for the files for which you did not provide contents (data.json, background.js) and indeed, I get the same error you get when I try to run the Gulp code you show. However, if I switch to calling Browserify directly, I do not get any error. Here is the code I have:
const gulp = require("gulp");
const browserify = require("browserify");
const source = require('vinyl-source-stream');
gulp.task('browserify', function () {
return browserify({
entries: ["./source/scripts/background.js",
"./source/scripts/modules/utils.js"],
debug: true,//for source maps
standalone: "foo",
})
.bundle()
.pipe(source('bundle.js')) // This sets the name of the output file.
.pipe(gulp.dest('./build/scripts/'));
});
You use gulp.src(['./source/scripts/**/*.js']) in your code, which means that Browserify will take all your .js files as entries into the bundle.
So I've put two entries in my code above, which manually replicates the pattern you use with the plugin. However, while Browserify does not produce an error with this setup, I suspect you don't actually want to have multiple entries. Typically, we pass one entry point to Browserify and let it trace the require calls to figure what it needs to pull.

Intern path error in browser client

I have a conventional recommended Intern directory structure:
MyProject
├── node_modules
│ ├── intern-geezer
│ │ ├── client.html
├── src
│ ├── myFunction.js
├── tests
│ ├── intern.js
│ ├── unit
│ │ ├── ps.js
with a very simple config:
useLoader: {
'host-node': 'dojo/dojo',
'host-browser': 'node_modules/dojo/dojo.js'
},
loader: {
packages: []
},
suites: [ 'tests/unit/ps' ]
and tests:
define(function (require) {
var tdd = require('intern!tdd');
var assert = require('intern/chai!assert');
// Global function to test, not an AMD module
var parseF = require('src/myFunction.js');
var he = require('tests/he');
tdd.suite('My tests', function() {
//etc
});
});
````
but when I open the browser client the loader is looking for the test suite inside the intern-geezer directory:
I am not setting a baseUrl in the config (or in the browser URL). I didn't have this trouble going through the regular (non-geezer) intern tutorial. Since the baseUrl defaults to two directories up from client.html I don't see what I'm doing wrong. Thanks for any help. (Yes, I will need geezer for ancient IE. No, I do not want to rewrite the function I'm testing as an AMD module.)
The Intern loader doesn't know how to get to your tests because they haven't been registered as a package. When using the recommended directory structure, you'll want to also set up the recommended loader configuration so that Intern knows where to find your code and tests.
loader: {
packages: [
{ name: 'app', location: 'src/' },
{ name: 'tests', location: 'tests/' }
]
}
Then, update your tests to correctly find the code you need to test.
// Global function to test, not an AMD module
var parseF = require('app/myFunction.js');
Now, Intern should be able to correctly find the code and tests.

Gulp watch, incremental build

I'm struggling to make gulp-watch behave as I desire. This small project is tooling to build HTML5 emails templates from Jade+SASS, in a repeatable way. The directory structure is as such:
.
├── Gulpfile.coffee
├── Gulpfile.js
├── build
│   ├── hello-world.html
│   └── styles
│   └── ink.css
├── node_modules
│   ├── ...snip...
├── package.json
└── source
├── hello-world.jade
├── layouts
│   └── default.jade
└── styles
└── ink.scss
My wish list is thus:
Build all templates when styles or templates change. This is what I can't do
Don't have a seaerate "cold" start, always use the gulp incremental build. (This seems to work)
Live reload would reload the browser, that'd be cool. (This too)
The Gulpfile, in CoffeeScript notation for brevity is included below, it's predominantly based on the documentation Incremental rebuilding, including operating on full file sets.
gulp = require 'gulp'
inlineCss = require 'gulp-inline-css'
jade = require 'gulp-jade'
marked = require 'gulp-marked'
plumber = require 'gulp-plumber'
rename = require 'gulp-rename'
sass = require 'gulp-sass'
cached = require 'gulp-cached'
util = require 'gulp-util'
watch = require 'gulp-watch'
webserver = require 'gulp-webserver'
styleGlob = "source/styles/*.scss"
templateAndLayouysGlob = "source/**/*.jade"
templateGlob = "source/*.jade"
styleChangeHandler = (event) ->
if event.type is "deleted"
delete cached.caches.scripts[event.path]
templateChangeHandler = (event) ->
if event.type is "deleted"
delete cached.caches.templates[event.path]
gulp.task "styleWatcher", ->
gulp.src(styleGlob)
.pipe(cached('styles'))
.pipe(watch(styleGlob))
.pipe(sass())
.pipe(gulp.dest("build/styles"))
.on('error', util.log)
gulp.task "templateWatcher", ->
gulp.src(templateGlob)
.pipe(cached('templates'))
.pipe(watch(templateGlob))
.pipe(jade(pretty: true))
.pipe(inlineCss())
.pipe(gulp.dest("build/"))
.on('error', util.log)
gulp.task 'webserver', ->
buildPath = 'build/'
gulp.src(buildPath)
.pipe(webserver({
livereload: true,
directoryListing: {
enable: true,
path: buildPath
},
open: true
}))
gulp.task "watch", ->
styleWatcher = gulp.watch(styleGlob, ["styleWatcher"])
styleWatcher.on 'change', styleChangeHandler
templateWatcher = gulp.watch(templateGlob, ["templateWatcher"])
templateWatcher.on 'change', templateChangeHandler
# I would expect this to fire when something in build/styles/*.css
# is updated by the style watcher?
templateStyleWatcher = gulp.watch('build/styles/*.css', ["templateWatcher"])
templateStyleWatcher.on 'change', templateChangeHandler
gulp.task "default", ["styleWatcher", "templateWatcher", "watch", "webserver"]
If it were possible, and I'd written this watcher in GNU Make or similar, I would have had the option to express that build/, and rely on the tooling to rebuild those files if the ones upon which they depend are out of date.
I've seen that there are a number of gulp-<something about inlining> plugins, but none of them make clear whether they support this conditional recompilation by watching paths that were imported for changes (I doubt it).
Given my background in systems programming, I may well be approaching Javascript build tooling in a completely incorrect way.

Categories

Resources