How to give an Order to the files compiled with coffeebar - javascript

I would like to be able to include the file with a given order while compiling my coffeescript files into js with coffeebar.
I would like to have the files settings.coffee, constants.coffee included first
--
|-- settings.coffee
|-- constants.coffee
|-- page1.coffee
|-- page2.coffee
Code Snippet
fs = require 'fs'
{exec, spawn} = require 'child_process'
util = require 'util'
task 'watch', 'Coffee bar Combine and build', ->
coffee = spawn 'coffeebar', ['-w','-o','./../js/main/kc.js', './']
coffee.stdout.on 'data', (data) ->
console.log data.toString().trim()
invoke 'minify'
task 'minify', ' Minify JS File', ->
file = "./../js/main/kc"
util.log "Minifiying #{file}.js"
exec "uglifyjs #{file}.js > #{file}.min.js", (err,stdout,stderr) ->
if err
util.log "Error minifiying file"
util.log err
else
util.log "Minified to #{file}.min.js"
util.log '----------------------------'
For now the script is only compiling the whole thing together according to its own logic.
I would appreciate any help on this.

It seems like you have 3 potential solutions, but all of them not so elegant:
I'm not sure, but try to set inputPaths argument of coffeebar(inputPaths, [options]) as explicit array of paths with file names, where you can set order of array elements as you need
try to rename files with num prefixes like 01_settiings.coffee and so on, in order what you need, so coffeebar will process it in this order
you can use extra plugin, like rigger to include all files you need in desired sequence in one root file, and process this file with coffeebar

Related

How to use a glob pattern in the scripts section of angular.json?

I have a hybrid AngularJS/Angular application that will take some time to complete migration to fully be an Angular app. While this process occurs, I'd like to move away from the previous build system to using the CLI and webpack to manage all of the old AngularJS scripts as well. This is possible as I've done it before by adding all of my scripts to the scripts section in angular.json like the following:
"scripts": [
"src/app/angularjs/app.js",
"src/app/angularjs/controllers/main.js",
"src/app/angularjs/services/someService.js",
"src/app/angularjs/controllers/someController.js"
],
This works well and the CLI builds via ng serve and ng build continue to work for the hybrid bootstrapped app as needed. The problem I'm running into now is manually listing each file for the current application I'm migrating is not ideal. I have hundreds of scripts that need to be added, and what I need is to be able to use a globbing pattern like the following:
"scripts": [
"src/app/angularjs/**/*.js"
],
The problem is this syntax from what I can tell is not supported. The glob pattern is supported in the assets section of angular.json as stated here but not in the scripts section: https://angular.io/guide/workspace-config#assets-configuration
In the scripts section I can't find a similar solution. It does have an expanded object API, but nothing that solves the problem I can tell to select all .js files from a particular directory as listed here: https://angular.io/guide/workspace-config#styles-and-scripts-configuration
Is it possible by some means to use a glob pattern or similar approach to select all files of a directory for the scripts section in angular.json so I don't have to manually list out hundreds of individual .js files?
The Bad News
The scripts section does not support the same glob patterns that the assets section does.
The Good News(?)
Since you're transitioning away from AngularJS, you hopefully won't have any new files to import in the future, so you could just generate the list of all the files you need to import.
Make your way to the src/app/angular directory and run the following:
find . -iregex '.*\.\(js\)' -printf '"%p",\n'
That will give you your list, already quoted for your convenience. You may need to do a quick search/replace (changing "." to "src/app/angularjs"), and don't forget to remove the last comma, but once you've done that once you should be all set.
The Extra News
You can further filter out unwanted files with -not, so (per your comment) you might do:
find . -iregex '^.*\.js$' -not -iregex '^.*_test\.js$' -printf '"%p",\n'
And that should give you all your .js files without your _test.js files.
KISS
Of course, this isn't a complex pattern, so as #atconway points out below, this will work just as well:
find . -iname "*.js" -not -iname "*_test.js" -printf '"%p",\n'
I'll keep the above, though, for use in situations where the full power of regex might come in handy.
I wanted to extend an anser of #JasonVerber and here is a Node.JS code and therefore (I believe) cross-platform.
Firstly install find package and then save contents from the snippet in some file.js.
Afterwards, specify paths so that they resolve to where you wan't to get your files from and where to put the resulting file to.
After that node file-name.js and this will save all found file paths to the resultPath in result.txt ready to Ctrl+A, Ctrl+C, Ctrl+V.
const find = require('find');
const path = require('path');
const fs = require('fs');
// BEFORE USAGE INSTALL `find` package
// Path to the folder where to look for files
const sourcePath = path.resolve(path.join(__dirname, 'cordova-app', 'src'));
// Path that will be removed from absolute path to files
const pathToRemove = path.resolve(path.join(__dirname, 'cordova-app'));
// Path where to put result.txt
const resultPath = path.resolve(path.join(__dirname, './result.txt'));
// Collects the file paths
const res = [];
// Path with replaced \ onto /
const pathToRemovehReplaced = pathToRemove.replace(/\\/g, '/');
// Get all fils that match a regex
find.eachfile(/\.js$/, sourcePath, file => {
// First remove all \ with / and then remove the path from root to source so that only relative path is left
const fileReplaced = file.replace(/\\/g, '/').replace(`${pathToRemovehReplaced}/`, '');
// Surround with quoutes
res.push(`"${fileReplaced}"`);
}).end(() => {
// Write file and concatenate results with newline and commas
fs.writeFileSync(resultPath, res.join(',\r\n'), 'utf8');
console.log('DONE!');
});
The result I got while testing (/\.ts$/ for regex)
"src/app/app.component.spec.ts",
"src/app/app.component.ts",
"src/app/app.module.ts",
"src/environments/environment.prod.ts",
"src/environments/environment.ts",
"src/main.ts",
"src/polyfills.ts",
"src/test.ts"

Webpack compile all files in a folder

So I'm using Laravel 5.4 and I use webpack to compile multiple .js files in 1 big js file.
const { mix } = require('laravel-mix');
// Compile all CSS file from the theme
mix.styles([
'resources/assets/theme/css/bootstrap.min.css',
'resources/assets/theme/css/main.css',
'resources/assets/theme/css/plugins.css',
'resources/assets/theme/css/themes.css',
'resources/assets/theme/css/themes/emerald.css',
'resources/assets/theme/css/font-awesome.min.css',
], 'public/css/theme.css');
// Compile all JS file from the theme
mix.scripts([
'resources/assets/theme/js/bootstrap.min.js',
'resources/assets/theme/js/app.js',
'resources/assets/theme/js/modernizr.js',
'resources/assets/theme/js/plugins.js',
], 'public/js/theme.js');
This is my webpack.mix.js to do it (same for css). But I want to get something like: resources/assets/theme/js/* to get all files from a folder. So when I make a new js file in the folder that webpack automatically finds it, and compile it when I run the command.
Does someone know how to this?
Thanks for helping.
If anyone wants the code to compile all sass/less/js files in a directory to a different directory with the same filename you can use this:
// webpack.mix.js
let fs = require('fs');
let getFiles = function (dir) {
// get all 'files' in this directory
// filter directories
return fs.readdirSync(dir).filter(file => {
return fs.statSync(`${dir}/${file}`).isFile();
});
};
getFiles('directory').forEach(function (filepath) {
mix.js('directory/' + filepath, 'js');
});
Wildcards are actually allowed using the mix.scripts() method, as confirmed by the creator in this issue. So your call should look like this:
mix.scripts(
'resources/assets/theme/js/*.js',
'public/js/theme.js');
I presume it works the same for styles, since they use the same method to combine the files.
Hope this helps you.

How to rename the original files of scripts in index.html using gulp?

I've written a gulp task to rename files so that they can be versioned. The problem is that the filenames of the files that the index.html scripts reference are not changed.
For example, in my index.html:
<script src=pub/main_v1.js"></script>
But if you actually navigate through the build folder to the subdirectory pub, you will find main.js.
Here is the custom gulp task:
const gulpConcat = require('gulp-concat');
const gulpReplace = require('gulp-replace');
const version = require('./package.json').version;
gulp.task('version', function () {
var vsn = '_' + version + '.js';
gulp.src('scripts/**/*.js')
.pipe(gulpConcat(vsn))
.pipe(gulp.dest('./prodBuild'));
return gulp.src('./prodBuild/index.html', { base: './prodBuild' })
.pipe(gulpReplace(/* some regex */, /* append vsn */))
.pipe(gulp.dest('./prodBuild'));
});
What do I need to fix/add so that the original filename changes to match that in the script tag?
Note: According to the gulp-concat docs, I should be able to find the concated files at prodBuild/[vsn], where [vsn] is _v1.js. However, it is no where to be found.
Update: The files rename properly in index.html, but I can't seem to get the renaming of the original files to work. Here's a snapshot of my build directory:
prodBuild/
pub/
main.js
someDir/
subDirA/
// unimportant stuff
subDirB/
file2.js
file3.js
// ...other files and folders...
EDIT:
The issue is that you return only one of the two tasks. The first task is simply ignored by gulp, since it is not returned. A simple solutions: Split it into two tasks, and reference the one from the other, like in this SO answer.
Old Answer
This looks like a perfect case for the gulp-rename. You could simply pipe your scripts through gulp-rename, like this:
.pipe(rename(function (path) {
path.basename += vsn;
path.extname = ".js"
}))
Gulp concat is, AFAIK, made for the concatination of files, not particularly for the renaming of them.

Compiling dynamically required modules with Browserify

I am using Browserify to compile a large Node.js application into a single file (using options --bare and --ignore-missing [to avoid troubles with lib-cov in Express]). I have some code to dynamically load modules based on what is available in a directory:
var fs = require('fs'),
path = require('path');
fs.readdirSync(__dirname).forEach(function (file) {
if (file !== 'index.js' && fs.statSync(path.join(__dirname, file)).isFile()) {
module.exports[file.substring(0, file.length-3)] = require(path.join(__dirname, file));
}
});
I'm getting strange errors in my application where aribtrary text files are being loaded from the directory my compiled file is loaded in. I think it's because paths are no longer set correctly, and because Browserify won't be able to require() the correct files that are dynamically loaded like this.
Short of making a static index.js file, is there a preferred method of dynamically requiring a directory of modules that is out-of-the-box compatible with Browserify?
This plugin allows to require Glob patterns: require-globify
Then, with a little hack you can add all the files on compilation and not executing them:
// Hack to compile Glob files. Don´t call this function!
function ಠ_ಠ() {
require('views/**/*.js', { glob: true })
}
And, for example, you could require and execute a specific file when you need it :D
var homePage = require('views/'+currentView)
Browserify does not support dynamic requires - see GH issue 377.
The only method for dynamically requiring a directory I am aware of: a build step to list the directory files and write the "static" index.js file.
There's also the bulkify transform, as documented here:
https://github.com/chrisdavies/tech-thoughts/blob/master/browserify-include-directory.md
Basically, you can do this in your app.js or whatever:
var bulk = require('bulk-require');
// Require all of the scripts in the controllers directory
bulk(__dirname, ['controllers/**/*.js']);
And my gulpfile has something like this in it:
gulp.task('js', function () {
return gulp.src('./src/js/init.js')
.pipe(browserify({
transform: ['bulkify']
}))
.pipe(rename('app.js'))
.pipe(uglify())
.pipe(gulp.dest('./dest/js'));
});

How to have a the docpad grunt skeleton min vendor js files with live reload

I'm using skeleton #2, HTML5BP + Grunt. The first time I docpad run the following happens:
info: LiveReload listening to new socket on channel /docpad-livereload
Performing writeFiles (postparing) at 0/1 0% [...] Running "min:js" (min) task
File "../out/scripts/all.min.js" created.
Uncompressed size: 298495 bytes.
Compressed size: 38257 bytes gzipped (106756 bytes minified).
Which is as is supposed to be. However using the livereload plugin if I change a template or document file, I get:
--Running "min:js" (min) task
File "../out/scripts/all.min.js" created.
Uncompressed size: 0 bytes.
Editing my script.js throws it into the mix, but none of my vendor js files are rendered with it, which is just as useless. grunt-cssmin renders all scss/css files grunt-config.json regardless, which works fine. Moving my js from /files/vendor to /documents/scripts didn't change this behavior.
I've done a little poking around, but I'm new to grunt and nothing jumped out at me.
It'd be nice if I could either:
a) have all JS files in grunt-config.json minned and zipped each time
b) not have grunt min js files in development environment
As is if I want to make any changes to something regarding javascript, I need to ctrl-c docpad and then run it again, which is meh.
Not ideal, but effective enough:
events:
# Write After
# Used to minify our assets with grunt
writeAfter: (opts,next) ->
# Prepare
docpad = #docpad
rootPath = docpad.config.rootPath
balUtil = require 'bal-util'
_ = require 'underscore'
# Make sure to register a grunt `default` task
command = ["#{rootPath}/node_modules/.bin/grunt", 'default']
# Execute
balUtil.spawn command, {cwd:rootPath,output:true}, ->
src = []
gruntConfig = require './grunt-config.json'
_.each gruntConfig, (value, key) ->
src = src.concat _.flatten _.pluck value, 'src'
#_.each src, (value) ->
# balUtil.spawn ['rm', value], {cwd:rootPath, output:false}, ->
#balUtil.spawn ['find', '.', '-type', 'd', '-empty', '-exec', 'rmdir', '{}', '\;'], {cwd:rootPath+'/out', output:false}, ->
next()
# Chain
#
The three lines around "balUtil" which perform find/rm commands were commented out.
Not ideal since the "uncompressed" files are left around -- but that's not really the end of the world. Live-reloading to empty pages was a tad more frustrating, ultimately.
There could be a way to further enhance this to detect a live reload (development) vs generating a build for production, but I haven't grokked that yet.

Categories