Is there a way to use browserify-shim without package.json? - gulp

I need to use browserify-shim for some of my browserify dependencies, but I can't edit my package.json. I'm using browserify inside of gulp. It is possible to specify all of the package.json portion exclusibely form the API? I'm envisioning something like this:
return gulp.src('glob/path/to/my/main/js/file.js')
.pipe(browserify({
debug: false,
transform: ['browserify-shim'],
shim: {
'jquery': {
exports: 'jQuery'
}
}
}));
Then, my output with repalce var $ = require('jquery'); with var $ = jQuery;, since we are now utilizing jQuery as a global. Is this possible? Whne

You could use exposify transform in that case. browserify-shim is actially based on it and is written by the same guy.
E.g.:
return browserify('glob/path/to/my/main/js/file.js', { debug: false })
.transform('exposify', { expose: {'jquery': 'jQuery' }})

gulpfile.js
gulp = require('gulp')
browserify = require('gulp-browserify')
gulp.task('browserify', function(){
var src = 'test.js'
gulp.src(src)
.pipe(browserify({
shim: {
jQuery: {
path: './bowser_components/jquery/dist/jquery.min.js',
exports: '$'
}
}
}))
.pipe(gulp.dest('./build/js'))
})
test.js
$ = require('jQuery')
console.log($);

Related

Transpile ES6 import/export with babel 6 and gulp

I would like to use ES6 import / export. I use Gulp 3.9 with babel.js 6.
I want to import functions.js into form.js.
I get the following error:
ReferenceError: require is not defined
== MY SETUP ==
functions.js
var helper = {
insertAfter: function(el, elParent) {
elParent.parentNode.insertBefore(el, elParent.nextSibling);
},
resetTextfield: function(el) {
let reinitTextfield = new mdc.textField.MDCTextField(el);
let label = el.firstElementChild.nextElementSibling;
label.classList.remove('mdc-text-field__label--float-above');
reinitTextfield.value = '';
}
}
// Export
export default helper;
form.js
// Import functions.js
import helper from './functions.js';
My Gulp task:
// babel js task - transpile our Javascript into the build directory
gulp.task("js-babel", () => {
$.fancyLog("-> Transpiling Javascript via Babel...");
return gulp.src(pkg.globs.babelJs)
.pipe($.plumber({errorHandler: onError}))
.pipe($.newer({dest: pkg.paths.build.js}))
.pipe($.babel())
.pipe($.size({gzip: true, showFiles: true}))
.pipe(gulp.dest(pkg.paths.build.js));
});
.babelrc:
{
"presets": ["es2015"],
"compact": true
}
I thought babel.js transpiles the JS and I can use import / export.
Now, am I reading that I need Browserify with Babelify ?!
Will that replace my "js-babel" task?
How should I rebuild my task?

foundation-sites 6 replacing panini for jekyll

I'm looking to extend a zurb foundation for sites 6 site and use jekyll instead of panini to render the HTML. I'm using the out of the box ZURB foundation prototype template that includes ES6 + webpack. I want foundation to handle all the SASS and JS compiling and I also want to retain the browsersync functionality. I just want to know the best approach for modifying the gulp file to integrate jekyll, this is so I can work with GitHub Pages.
Here is what the default gulp.babel.js file looks like:
'use strict';
import plugins from 'gulp-load-plugins';
import yargs from 'yargs';
import browser from 'browser-sync';
import gulp from 'gulp';
import panini from 'panini';
import rimraf from 'rimraf';
import sherpa from 'style-sherpa';
import yaml from 'js-yaml';
import fs from 'fs';
import webpackStream from 'webpack-stream';
import webpack2 from 'webpack';
import named from 'vinyl-named';
// Load all Gulp plugins into one variable
const $ = plugins();
// Check for --production flag
const PRODUCTION = !!(yargs.argv.production);
// Load settings from settings.yml
const { COMPATIBILITY, PORT, UNCSS_OPTIONS, PATHS } = loadConfig();
function loadConfig() {
let ymlFile = fs.readFileSync('config.yml', 'utf8');
return yaml.load(ymlFile);
}
// Build the "dist" folder by running all of the below tasks
gulp.task('build',
gulp.series(clean, gulp.parallel(pages, sass, javascript, images, copy), styleGuide));
// Build the site, run the server, and watch for file changes
gulp.task('default',
gulp.series('build', server, watch));
// Delete the "dist" folder
// This happens every time a build starts
function clean(done) {
rimraf(PATHS.dist, done);
}
// Copy files out of the assets folder
// This task skips over the "img", "js", and "scss" folders, which are parsed separately
function copy() {
return gulp.src(PATHS.assets)
.pipe(gulp.dest(PATHS.dist + '/assets'));
}
// Copy page templates into finished HTML files
function pages() {
return gulp.src('src/pages/**/*.{html,hbs,handlebars}')
.pipe(panini({
root: 'src/pages/',
layouts: 'src/layouts/',
partials: 'src/partials/',
data: 'src/data/',
helpers: 'src/helpers/'
}))
.pipe(gulp.dest(PATHS.dist));
}
// Load updated HTML templates and partials into Panini
function resetPages(done) {
panini.refresh();
done();
}
// Generate a style guide from the Markdown content and HTML template in styleguide/
function styleGuide(done) {
sherpa('src/styleguide/index.md', {
output: PATHS.dist + '/styleguide.html',
template: 'src/styleguide/template.html'
}, done);
}
// Compile Sass into CSS
// In production, the CSS is compressed
function sass() {
return gulp.src('src/assets/scss/app.scss')
.pipe($.sourcemaps.init())
.pipe($.sass({
includePaths: PATHS.sass
})
.on('error', $.sass.logError))
.pipe($.autoprefixer({
browsers: COMPATIBILITY
}))
// Comment in the pipe below to run UnCSS in production
//.pipe($.if(PRODUCTION, $.uncss(UNCSS_OPTIONS)))
.pipe($.if(PRODUCTION, $.cleanCss({ compatibility: 'ie9' })))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest(PATHS.dist + '/assets/css'))
.pipe(browser.reload({ stream: true }));
}
let webpackConfig = {
rules: [
{
test: /.js$/,
use: [
{
loader: 'babel-loader'
}
]
}
]
}
// Combine JavaScript into one file
// In production, the file is minified
function javascript() {
return gulp.src(PATHS.entries)
.pipe(named())
.pipe($.sourcemaps.init())
.pipe(webpackStream({module: webpackConfig}, webpack2))
.pipe($.if(PRODUCTION, $.uglify()
.on('error', e => { console.log(e); })
))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest(PATHS.dist + '/assets/js'));
}
// Copy images to the "dist" folder
// In production, the images are compressed
function images() {
return gulp.src('src/assets/img/**/*')
.pipe($.if(PRODUCTION, $.imagemin({
progressive: true
})))
.pipe(gulp.dest(PATHS.dist + '/assets/img'));
}
// Start a server with BrowserSync to preview the site in
function server(done) {
browser.init({
server: PATHS.dist, port: PORT
});
done();
}
// Reload the browser with BrowserSync
function reload(done) {
browser.reload();
done();
}
// Watch for changes to static assets, pages, Sass, and JavaScript
function watch() {
gulp.watch(PATHS.assets, copy);
gulp.watch('src/pages/**/*.html').on('all', gulp.series(pages, browser.reload));
gulp.watch('src/{layouts,partials}/**/*.html').on('all', gulp.series(resetPages, pages, browser.reload));
gulp.watch('src/assets/scss/**/*.scss').on('all', sass);
gulp.watch('src/assets/js/**/*.js').on('all', gulp.series(javascript, browser.reload));
gulp.watch('src/assets/img/**/*').on('all', gulp.series(images, browser.reload));
gulp.watch('src/styleguide/**').on('all', gulp.series(styleGuide, browser.reload));
}
I assume as part of the jekyll build/rebuild I would need to use the keep-files config setting so when jekyll clobbers the output directory file don't get overwritten.
Appreciate any help
Thanks
Jekyll is a different solution than Panini and uses Ruby
https://jekyllrb.com/docs/installation/
In general you might need some git hook or Travis config.
https://github.com/DanielRuf/testblog/blob/source/.travis.yml
https://github.com/DanielRuf/testblog/blob/source/Rakefile

Vue.js dynamic component loading + hot reload

I have Laravel 5.3.21 application with Vue.js 1.0.28
I'm using hot-reload workflow with browserify-hmr plugin.
Here is the simple gulpfile.js used to achieve that:
var elixir = require('laravel-elixir');
var gutil = require('gulp-util');
require('laravel-elixir-browserify-official');
require('laravel-elixir-vueify');
// If 'gulp watch' is run
if (gutil.env._.indexOf('watch') > -1) {
// Enable watchify for faster builds
elixir.config.js.browserify.watchify.enabled = true;
// Add the browserify HMR plugin
elixir.config.js.browserify.plugins.push({
name: 'browserify-hmr',
options: {
url: 'http://1.2.3.4:2096',
hostname: '1.2.3.4',
port: 2096
}
})
}
elixir.config.js.browserify.watchify.options.poll = true;
elixir(function (mix) {
mix.copy('node_modules/datatables.net-bs/css/dataTables.bootstrap.css',
'resources/assets/css/vendor/dataTables.bootstrap.css');
mix.styles([
'vendor/dataTables.bootstrap.css'
]);
mix.sass('app.scss');
mix.browserify('app.js');
});
I need to load components dynamically from the resources/assets/js/views/ folder, so I could make my front-end code modular and based on current route name $Laravel->routeName = request()->route()->getName() in Laravel.
For example:
// Global Settings.
Route::get('admin/settings', 'Admin#settings')
->name('admin_global_settings');
Then in resources/assets/js/views/admin/admin_global_settings.js I have code to initialize Vue.js component and register it with Vue.js instance:
var FeaturedOpportunities = require( '../../components/Featured-Opportunities.vue' );
window.Vue.component('FeaturedOpportunities', FeaturedOpportunities);
That is all nice but here is the problem in resources/assets/js/app.js:
window.Vue = require('vue');
require('vue-resource');
Vue.http.interceptors.push((request, next) => {
request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);
next();
});
// Problem is here, have to keep track of all my routes and their corresponding modules:
var routes = {
'organization_invites_roles': function () {
require('./views/organization/organization_invites_roles');
},
'admin_global_settings': function () {
require('./views/admin/admin_global_settings');
},
};
// Is there a way to load it dynamically?
if (Laravel.routeName) {
if (routes[Laravel.routeName]) {
routes[Laravel.routeName]();
}
}
new Vue({
el: 'body',
components: {
},
ready() {
console.log('Vue and Vueify all set to go!');
}
});
I've found some way that could probably solve this issue: Compiling dynamically required modules with Browserify but not sure if this applicable for my case.

Get "file basename" in gulp-replacer-task

I'm manipulating a set of files and I am using gulp-replacer-task to replace the content of processed files with "strings" based on the basename or path of the file currently in the pipe-line.
How do i get at the file's properties currently in the pipe-line ?
gulp.task('svgbuild', function() {
return gulp.src('./src/*.svg')
.pipe(replace({
patterns: [
{
match: /STRING_TO_MATCH/g,
replacement: function() {
// how to get the basename of the "file" in the stream;
var str = 'file.basename'
// manipulate to get replacement string based on basename
var repl = str.toUpperCase()+'-inc'
return repl;
}
}
]
}))
});
Somewhat later than I hoped, but it appears I found a solution for the problem using gulp-tap. This is what my gulpfile.js looks like:
var gulp = require('gulp'),
path = require('path'),
replace = require('gulp-replace-task'),
tap = require('gulp-tap');
gulp.task('svgbuild', function () {
return gulp.src('*.txt')
.pipe(tap(function (file) {
return gulp.src(file.path)
.pipe(replace({
patterns: [
{
match: /foo/g,
replacement: function () {
var ext = path.extname(file.path),
base = path.basename(file.path, ext);
return base.toUpperCase() + '-inc'
}
}
]
}))
.pipe(gulp.dest('build'));
}));
});
I think you must look for the solution in Node.js. Maybe this helps: https://nodejs.org/api/path.html?

Gulp to combine bower files

I'm aware this has probably been asked before, but I can't seem to be able to ask Google the right questions to find what I need. So I'm possibly thinking about this in the wrong way.
Basically, I need to know if there is a way to use Gulp with Bower so that all css files in subdirectories under bower_components are combined into one styles.css, all js files in subdirectories under bower_components are combined into one scripts.js. Kind of how assetic works in symfony2 to combine assets into single files. Does each 'built' file in each bower_componets subdirectory have to be linked to manually (in the Gulp config file), or is it more common to loop through them programatically?
Thanks
Would something like the below help? It loops through all css files in my 'src' directory and spits out one css file in the 'dist' folder. It does the same for my js files:
// Config
var requireJsRuntimeConfig = vm.runInNewContext(fs.readFileSync('src/app/require.config.js') + '; require;');
requireJsOptimizerConfig = merge(requireJsRuntimeConfig, {
out: 'scripts.js',
baseUrl: './src',
name: 'app/startup',
paths: {
requireLib: 'bower_modules/requirejs/require'
},
include: [
'requireLib',
'components/nav-bar/nav-bar',
'components/home-page/home',
'text!components/about-page/about.html'
],
insertRequire: ['app/startup'],
bundles: {
// If you want parts of the site to load on demand, remove them from the 'include' list
// above, and group them into bundles here.
// 'bundle-name': [ 'some/module', 'another/module' ],
// 'another-bundle-name': [ 'yet-another-module' ]
}
});
// Discovers all AMD dependencies, concatenates together all required .js files, minifies them
gulp.task('js', function () {
return rjs(requireJsOptimizerConfig)
.pipe(uglify({ preserveComments: 'some' }))
.pipe(gulp.dest('./dist/'));
});
// Concatenates CSS files, rewrites relative paths to Bootstrap fonts, copies Bootstrap fonts
gulp.task('css', function () {
var bowerCss = gulp.src('src/bower_modules/components-bootstrap/css/bootstrap.min.css')
.pipe(replace(/url\((')?\.\.\/fonts\//g, 'url($1fonts/')),
appCss = gulp.src('src/css/*.css'),
combinedCss = es.concat(bowerCss, appCss).pipe(concat('css.css')),
fontFiles = gulp.src('./src/bower_modules/components-bootstrap/fonts/*', { base: './src/bower_modules/components-bootstrap/' });
return es.concat(combinedCss, fontFiles)
.pipe(gulp.dest('./dist/'));
});
there is a way and its honestly really simple. you can install "gulp-run" to your npm devDependencies and then use the run to execute bower install.
var gulp = require('gulp'),
del = require('del'),
run = require('gulp-run'),
sass = require('gulp-sass'),
cssmin = require('gulp-minify-css'),
browserify = require('browserify'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
jshint = require('gulp-jshint'),
browserSync = require('browser-sync'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
reactify = require('reactify'),
package = require('./package.json'),
reload = browserSync.reload;
/**
* Running Bower
*/
gulp.task('bower', function() {
run('bower install').exec();
})
/**
* Cleaning lib/ folder
*/
.task('clean', function(cb) {
del(['lib/**'], cb);
})
/**
* Running livereload server
*/
.task('server', function() {
browserSync({
server: {
baseDir: './'
}
});
})
/**
* sass compilation
*/
.task('sass', function() {
return gulp.src(package.paths.sass)
.pipe(sass())
.pipe(concat(package.dest.style))
.pipe(gulp.dest(package.dest.lib));
})
.task('sass:min', function() {
return gulp.src(package.paths.sass)
.pipe(sass())
.pipe(concat(package.dest.style))
.pipe(cssmin())
.pipe(gulp.dest(package.dest.lib));
})
/**
* JSLint/JSHint validation
*/
.task('lint', function() {
return gulp.src(package.paths.js)
.pipe(jshint())
.pipe(jshint.reporter('default'));
})
/** JavaScript compilation */
.task('js', function() {
return browserify(package.paths.app)
.transform(reactify)
.bundle()
.pipe(source(package.dest.app))
.pipe(gulp.dest(package.dest.lib));
})
.task('js:min', function() {
return browserify(package.paths.app)
.transform(reactify)
.bundle()
.pipe(source(package.dest.app))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest(package.dest.lib));
})
/**
* Compiling resources and serving application
*/
.task('serve', ['bower', 'clean', 'lint', 'sass', 'js', 'server'], function() {
return gulp.watch([
package.paths.js, package.paths.jsx, package.paths.html, package.paths.sass
], [
'lint', 'sass', 'js', browserSync.reload
]);
})
.task('serve:minified', ['bower', 'clean', 'lint', 'sass:min', 'js:min', 'server'], function() {
return gulp.watch([
package.paths.js, package.paths.jsx, package.paths.html, package.paths.sass
], [
'lint', 'sass:min', 'js:min', browserSync.reload
]);
});
what is really beautiful with this setup I just posted is this is making a custom gulp run called "serve" that will run your setup with a development server (with live reload and much better error intelligence) all you have to do is go to your directory and type "gulp serve" and it'll run bower install and build everything for you. obviously the folder structure is different so you will need to make some modifications, but hopefully this shows how you can run bower with gulp :)
Something like the below was what I was looking for, except I don't like having to add the paths manually. This is why I prefer something like CommonJS for Javascript. I definitely remember seeing a way in which CSS files were picked up automatically from the bower_components folder, I believe it was in the Wordpress Roots project (based on the settings/overrides in bower.json).
gulp.task('css', function () {
var files = [
'./public/bower_components/angular-loading-bar/build/loading-bar.css',
'./public/bower_components/fontawesome/css/font-awesome.css'
];
return gulp.src(files, { 'base': 'public/bower_components' })
.pipe(concat('lib.css'))
.pipe(minifyCss())
.pipe(gulp.dest('./public/build/css/')
);
});
gulp.task('js-lib', function () {
var files = [
'public/bower_components/jquery/dist/jquery.js',
'public/bower_components/bootstrap-sass/assets/javascripts/bootstrap.js'
];
return gulp.src(files, { 'base': 'public/bower_components/' })
.pipe(sourcemaps.init())
.pipe(uglify({ mangle: false }))
.pipe(concat('lib.js'))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/build/js/')
);
});
You can use gulp-main-bower-files library to add the main files of packages in .bower.json instead to declare them manually