I would appreciate some help fixing my file paths/setup/whatever I am doing wrong.
First off; this is my first time setting up Gulp, and I am NOT a pro.
I am setting up Gulp in an existing app, using wiredep and gulp-inject to read the file paths of my bower_components and custom .js files, and injecting these paths into my index.html.
The issue I am getting is; when running the app in the browser, none of the paths - except for the bower paths - are working, resulting in a whole lot of 404 errors: Not Found.
The path to read the file names is (example) './src/vendorScripts/', and this adds the file to the index.html as <script src="/src/vendorScripts/ChartFactory.js"></script>, whereas the path is supposed to be <script src="vedorScripts/ChartFactory.js"></script>.
This is my gulp.config.js file:
module.exports = function () {
var source = './src/';
var sourceScripts = './src/scripts/';
var sourceScriptsPlugins = './src/scripts/plugins/';
var vendorcripts = './src/vendorScripts/';
var vendorcriptsUsedInApp = './src/vendorScripts/usedInApp/';
var sourceScriptsSocialMedia = './src/socialMedia.module/';
var sourceScriptsCookiesModule = './src/cookies.module/';
var config = {
temp: './.temp/',
/**
* File paths
*/
// all js to vet
alljs: [
'./src/**/*.js',
'./*.js'
],
source: source,
index: source + 'index.html',
js: [
sourceScripts + '**/app.js',
sourceScriptsPlugins + '**/*.js',
vendorcriptsUsedInApp + '**/*.js',
sourceScripts + '**/*Controller.js',
sourceScriptsSocialMedia + '**/*.js',
sourceScriptsCookiesModule + '**/*.js',
sourceScripts + '**/*Directive.js',
sourceScripts + '**/*Filter.js',
sourceScripts + '**/*Service.js',
sourceScripts + '**/*Factory.js',
sourceScripts + '**/*Constant.js'
],
less: source + './src/styles/main.less',
/**
* Bower and NPM locations
*/
bower: {
json: require('./bower.json'),
directory: './bower_components/',
ignorePath: '../..'
}
};
config.getWiredepDefaultOptions = function (){
var options = {
bowerJson: config.bower.json,
directory: config.bower.directory,
ignorePath: config.bower.ignorePath
};
return options;
};
return config;
};
This is my gulpfile.js:
var gulp = require('gulp');
var args = require('yargs').argv;
var config = require('./gulp.config')();
var del = require('del');
var inject = require('gulp-inject');
var wiredep = require('wiredep').stream;
var $ = require('gulp-load-plugins')({ lazy: true });
gulp.task('vet', function () {
log('Analysing source with JSHint and JSCS');
return gulp
.src(config.alljs)
.pipe($.if(args.verbose, $.print()))
.pipe($.jscs())
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish', { verbose: true }))
.pipe($.jshint.reporter('fail'));
});
gulp.task('styles', ['clean-styles'], function () {
log('Compiling Less --> CSS');
return gulp
.src(config.less)
.pipe($.plumber())
.pipe($.less())
.pipe($.autoprefixer({ browsers: ['last 2 versions', '> 5%'] }))
.pipe(gulp.dest(config.temp));
});
gulp.task('clean-styles', function(){
var files = config.temp + '**/*.css';
return clean(files);
});
gulp.task('less-watcher', function(){
gulp.watch([config.less], ['styles']);
});
gulp.task('wiredep', function () {
// log('Wire up the bower css js and our app js into the html');
var options = config.getWiredepDefaultOptions();
return gulp
.src(config.index)
.pipe(wiredep(options))
.pipe($.inject(gulp.src(config.js)))
.pipe(gulp.dest(config.source))
.pipe($.jshint.reporter('jshint-stylish', { verbose: true }))
.pipe($.jshint.reporter('fail'));
});
//////////////
function clean(path){
log('Cleaning: ' + $.util.colors.blue(path));
return del(path); // returns a promise
}
function log(msg) {
if (typeof (msg) === 'object') {
for (var item in msg) {
if (msg.hasOwnProperty(item)) {
$.util.log($.util.colors.blue(msg[item]));
}
}
} else {
$.util.log($.util.colors.blue(msg));
}
}
This image shows my directory listing:
I would appreciate your advice!
I managed to resolve my issue making use of the following solution:
NOTE: gulp-inject takes various options that one can use to define the destination and other settings. You can read more on this on the official npm gulp-inject page: gulp-inject.
The options object below sorts out my issues with the relative path and root slash. I added this to my gulpfile.js:
var injectOptions = {
addRootSlash: false,
ignorePath: 'src/'
};
And then add the injectOptions to my gulp.task('wiredep'):
gulp.task('wiredep', function () {
var options = config.getWiredepDefaultOptions();
return gulp
.src(config.index)
.pipe(wiredep(options))
.pipe($.inject(gulp.src(config.js), injectOptions))
.pipe(gulp.dest(config.source))
.pipe($.jshint.reporter('jshint-stylish', { verbose: true }))
.pipe($.jshint.reporter('fail'));
});
The output is the desired script source:
<script src="vedorScripts/ChartFactory.js"></script>
Related
After changing gulp 3 to 4 I receive the error when I try to run gulp build:
Error: File not found with singular glob: /assets/css/argon.css (if this was purposeful, use `allowEmpty` option)
The code was working before with gulp 3 (as I was told) and I made a couple of changes to be able to work with gulp 4 as well. The error is received after all tasks has run correcltly.
File is located where it is looking for it:
And here is my gulpfile.js:
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var csscomb = require('gulp-csscomb');
var cleanCss = require('gulp-clean-css');
var cssnano = require('gulp-cssnano');
var composer = require('gulp-uglify/composer');
var concat = require('gulp-concat');
var del = require('del');
var imagemin = require('gulp-imagemin');
var htmlPrettify = require('gulp-html-prettify');
var gulp = require('gulp');
var gulpIf = require('gulp-if');
var gulpRun = require('gulp-run');
var gulpUtil = require('gulp-util');
var npmDist = require('gulp-npm-dist');
var postcss = require('gulp-postcss');
var runSequence = require('gulp4-run-sequence');
// var sass = require('gulp-sass');
var uglifyEs = require('uglify-es');
var uglify = composer(uglifyEs, console);
var rename = require('gulp-rename');
var useref = require('gulp-useref-plus');
var wait = require('gulp-wait');
var sass = require('gulp-sass')(require('sass'));
// Define paths
var paths = {
dist: {
base: 'dist',
img: 'dist/assets/img',
libs: 'dist/assets/vendor'
},
base: {
base: './',
node: 'node_modules'
},
src: {
base: './',
css: 'assets/css',
html: '**/*.html',
img: 'assets/img/**/*.+(png|jpg|gif|svg)',
js: 'assets/js/**/*.js',
scss: 'assets/scss/**/*.scss'
}
}
// Compile SCSS
gulp.task('scss', async function() {
return gulp.src(paths.src.scss)
.pipe(wait(500))
.pipe(sass().on('error', sass.logError))
.pipe(postcss([require('postcss-flexbugs-fixes')]))
.pipe(autoprefixer({
browsers: ['> 1%']
}))
.pipe(csscomb())
.pipe(gulp.dest(paths.src.css))
.pipe(browserSync.reload({
stream: true
}));
});
// Minify CSS
gulp.task('minify:css', async function() {
return gulp.src([
paths.src.css + '/argon.css'
])
.pipe(cleanCss())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest(paths.dist.base + '/css'))
});
// Concat JS files
gulp.task('concat:js', async function(done) {
files = [
paths.src.base + '/assets/js/components/license.js',
paths.src.base + '/assets/js/components/layout.js',
paths.src.base + '/assets/js/components/init/*js',
paths.src.base + '/assets/js/components/custom/*js',
paths.src.base + '/assets/js/components/maps/*js',
paths.src.base + '/assets/js/components/charts/*js',
paths.src.base + '/assets/js/components/vendor/*js'
];
return gulp
.src(files)
.pipe(concat("argon.js"))
.pipe(gulp.dest(paths.dist.base + '/js'));
done();
});
// Minify JS
gulp.task('minify:js', async function(cb) {
return gulp.src([
paths.dist.base + '/js/argon.js'
])
.pipe(uglify())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest(paths.dist.base + '/js'))
});
// Live reload
gulp.task('browserSync', async function() {
browserSync.init({
server: {
baseDir: [paths.src.base, paths.base.base]
},
})
});
// Watch for changes
gulp.task('watch', gulp.series('browserSync', 'scss', async function() {
gulp.watch(paths.src.scss, ['scss']);
gulp.watch(paths.src.js, browserSync.reload);
gulp.watch(paths.src.html, browserSync.reload);
}));
// Clean
gulp.task('clean:dist', async function() {
return del.sync(paths.dist.base);
});
// Copy CSS
gulp.task('copy:css', async function() {
return gulp.src([
paths.src.base + '/assets/css/argon.css'
])
.pipe(gulp.dest(paths.dist.base + '/css'))
});
// Copy JS
gulp.task('copy:js', async function() {
return gulp.src([
paths.src.base + '/assets/js/argon.js'
])
.pipe(gulp.dest(paths.dist.base + '/js'))
});
// Build
gulp.task('build', async function(callback) {
runSequence('clean:dist', 'scss', 'copy:css', 'copy:js', 'concat:js', 'minify:js', 'minify:css',
callback);
});
// Default
gulp.task('default', async function(callback) {
runSequence(['scss', 'browserSync', 'watch'],
callback
)
});
Any help would be appreciated :)
In copy:css you have this line:
paths.src.base + '/assets/css/argon.css'
where apparently your error is. The problem is your paths.src.base is defined as
base: './' to which you are adding /assets/css/argon.css so you end up with
.//assets/css/argon.css note the two leading backslashes.
Get rid of the leading backslash in the /assets/... and check the rest of your code for the same problem.
Also since you are using gulp4 get rid of runSequence - look at the documentation for gulp.series.
The goal is, transpiling ES6 scripts into ES5 and make them browser readable.
This works most with my node.js gulp task, but some of the script use "import" like
import EstaticoModule from '../../assets/js/helpers/module';
I would like to skip this "import" and more over delete this row from result.
Is there a param in "gulp-babel" to achieve this or has one another idea to make this in a better way?
Here is my gulp task:
'use strict';
/**
* #function `gulp js:lint1`
* #desc Lint JavaScript files (using `ESLint`).
*/
var gulp = require('gulp'),
helpers = require('require-dir')('../../helpers'),
webpack = require('webpack'),
babel = require("gulp-babel");
//babel = require("babelify");
//babel = require("babel-core");
//require("babel-core");
var taskName = 'js:lint1',
taskConfig = {
src: [
'source/assets/js/**/*.js',
'source/modules/**/*.js',
'source/pages/**/*.js',
'source/demo/modules/**/*.js',
'source/demo/pages/**/*.js',
'!source/modules/**/*.data.js',
'!source/pages/**/*.data.js',
'!source/demo/modules/**/*.data.js',
'!source/demo/pages/**/*.data.js',
'!source/modules/.scaffold/scaffold.js',
'!source/assets/js/libs/**/*.js',
'!source/assets/js/libs/wtscript.js'
],
watch: [
'./source/assets/js/**/*.js',
'./source/modules/**/*.js',
'./source/pages/**/*.js',
'./source/demo/modules/**/*.js',
'./source/demo/pages/**/*.js',
'!./source/modules/.scaffold/scaffold.js'
],
dest: './RSE/',
srcBase: './source/assets/js/'
}
gulp.task( taskName, function() {
var helpers = require('require-dir')('../../helpers'),
tap = require('gulp-tap'),
path = require('path'),
cached = require('gulp-cached'),
eslint = require('gulp-eslint');
return gulp.src(taskConfig.src, {
dot: true
})
.pipe(cached('linting'))
.pipe(eslint())
.pipe(eslint.formatEach())
.pipe(tap(function(file) {
if (file.eslint && file.eslint.errorCount > 0) {
helpers.errors({
task: taskName,
message: 'Linting error in file "' + path.relative('./source/', file.path) + '" (details above)'
});
}else{
console.log(file);
}
}))
.pipe(babel({
presets: [
'es2015',
'react'
],
plugins: [
// Work around some issues in IE
'transform-class-properties',
'transform-proto-to-assign',
['transform-es2015-classes', {
loose: true
}]
]
}))
.pipe(gulp.dest(taskConfig.dest))
;
});
module.exports = {
taskName: taskName,
taskConfig: taskConfig
};
I have found a way:
// EXCLUDE IMPORTS FROM STREAM
var content = file.contents.toString();
content = content.replace(/import/g, "//$&");
// RETURN STREAM INTO PIPE
file.contents = Buffer.from(content);
This will result in
//import EstaticoModule from '../../assets/js/helpers/module';
Here is the code in summary:
'use strict';
/**
* #function `gulp js:create:js:files`
* #desc Lint JavaScript files (using `ESLint`), EXCLUDE IMPORTS FROM STREAM and create separate js files in modules/%module% folder.
*/
var gulp = require('gulp'),
helpers = require('require-dir')('../../helpers'),
webpack = require('webpack'),
babel = require("gulp-babel");
var taskName = 'js:create:js:files',
taskConfig = {
src: [
'source/assets/js/**/*.js',
'source/modules/**/*.js',
'source/pages/**/*.js',
'source/demo/modules/**/*.js',
'source/demo/pages/**/*.js',
'!source/modules/**/*.data.js',
'!source/pages/**/*.data.js',
'!source/demo/modules/**/*.data.js',
'!source/demo/pages/**/*.data.js',
'!source/modules/.scaffold/scaffold.js',
'!source/assets/js/libs/**/*.js',
'!source/assets/js/libs/wtscript.js'
],
watch: [
'./source/assets/js/**/*.js',
'./source/modules/**/*.js',
'./source/pages/**/*.js',
'./source/demo/modules/**/*.js',
'./source/demo/pages/**/*.js',
'!./source/modules/.scaffold/scaffold.js'
],
dest: './build/',
srcBase: './source/assets/js/'
}
gulp.task( taskName, function() {
var helpers = require('require-dir')('../../helpers'),
tap = require('gulp-tap'),
path = require('path'),
cached = require('gulp-cached'),
eslint = require('gulp-eslint');
return gulp.src(taskConfig.src, {
dot: true
})
.pipe(cached('linting'))
.pipe(eslint())
.pipe(eslint.formatEach())
.pipe(tap(function(file) {
if (file.eslint && file.eslint.errorCount > 0) {
helpers.errors({
task: taskName,
message: 'Linting error in file "' + path.relative('./source/', file.path) + '" (details above)'
});
}else{
// EXCLUDE IMPORTS FROM STREAM
var content = file.contents.toString();
content = content.replace(/import/g, "//$&");
// RETURN STREAM INTO PIPE
file.contents = Buffer.from(content);
}
}))
.pipe(babel({
presets: [
'es2015'
,'react'
],
plugins: [
// Work around some issues in IE
'transform-class-properties',
'transform-proto-to-assign',
['transform-es2015-classes', {
loose: true
}]
]
}))
.pipe(gulp.dest(taskConfig.dest))
;
});
module.exports = {
taskName: taskName,
taskConfig: taskConfig
};
I'm trying to require a file with a variable in the path. Something like
const langCode = this.props.langCode; // en
let languageFile = require('../common/languages/' + langCode);
Where langCode can be fr, en, de, nl. Thus what I'm trying to get is for example
require('../common/languages/en');
When I type it without variable at the end, thus require('../common/languages/en'); it works good. But when I try with require('../common/languages/' + langCode); it won't work, doesn't matter that the value of the langCode is also en.
I get next error :
bundle.js:1 Uncaught Error: Cannot find module '../common/languages/en'
UPDATE
'use strict';
var gulp = require('gulp');
var connect = require('gulp-connect');
var open = require('gulp-open');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var concat = require('gulp-concat');
var babelify = require('babelify');
var sass = require('gulp-sass');
var merge = require('merge-stream'); // Merge all styles (css, sass and less) in one big bundle
var lint = require("gulp-eslint");
var config = {
port: 8001,
devBaseUrl: 'http://localhost',
paths: {
html: "./src/*.html",
externals: "./src/assets/externals/*.js",
js: "./src/**/*.js",
images: './src/assets/images/**/*',
fonts: './src/assets/css/fonts/*',
css: [
"./src/assets/css/*.css",
"./node_modules/toastr/package/toastr.css"
],
sass: './src/assets/css/*.scss',
dist: "./dist",
mainJS: "./src/main.js"
}
};
gulp.task('connect', ['watch'], function () {
connect.server({
root: ['dist'],
port: config.port,
base: config.devBaseUrl,
livereload: true,
fallback: './dist/index.html'
})
});
gulp.task('open', ['connect'], function () {
gulp.src('dist/index.html')
.pipe(open({uri: config.devBaseUrl + ":" + config.port + "/"}));
});
gulp.task('html', function () {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('externals', function () {
gulp.src(config.paths.externals)
.on('error', console.error.bind(console))
.pipe(concat('external.js'))
.pipe(gulp.dest(config.paths.dist + '/externals'))
.pipe(connect.reload());
});
gulp.task('js', function () {
browserify(config.paths.mainJS)
.transform('babelify', {presets: ['es2015', 'react']})
.bundle()
.on('error', console.error.bind(console))
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.paths.dist + '/scripts'))
.pipe(connect.reload());
});
gulp.task('images', function () {
gulp.src(config.paths.images)
.pipe(gulp.dest(config.paths.dist + '/images'));
});
gulp.task('styles', function () {
var cssStyles = gulp.src(config.paths.css)
.pipe(concat('styles.css'));
var sassStyles = gulp.src(config.paths.sass)
.pipe(sass())
.pipe(concat('styles.scss'));
var mergedStream = merge(cssStyles, sassStyles)
.pipe(concat('bundle.css'))
.pipe(gulp.dest(config.paths.dist + '/css'))
.pipe(connect.reload());
return mergedStream;
});
gulp.task('fonts', function () {
gulp.src(config.paths.fonts)
.pipe(gulp.dest(config.paths.dist + '/css/fonts'));
});
gulp.task('lint', function () {
return gulp.src(config.paths.js)
.pipe(lint())
.pipe(lint.format());
});
gulp.task('watch', function () {
gulp.watch(config.paths.html, ['html']);
gulp.watch(config.paths.js, ['js', 'lint']);
gulp.watch(config.paths.externals, ['externals', 'lint']);
gulp.watch([config.paths.css, config.paths.sass], ['styles']);
gulp.watch(config.paths.images, ['images']);
});
gulp.task('default', ['html', 'js', 'styles', 'externals', 'images', 'fonts', 'lint', 'open', 'watch']);
Most of JS bundlers cannot handle dynamic require mechanism.
Try to load all languages and switch them in runtime
let languages = {
en: require('../common/languages/en'),
ru: require('../common/languages/ru'),
de: require('../common/languages/de')
}
const langCode = this.props.langCode; // en
let languageFile = languages[langCode];
Are you using webpack as your bundler?
If so you need to be aware of it's dynamic requires mechanism.
Here is an issue that discusses it.
in your express.js server, set up a static directory containing any static.file:
const express = require('express')
const app = express()
app.use(express.static(path.join(__dirname, '../path_to/..', staticImages)))
react native component:
return <Image source={{ uri: `http://192.168.0.1:3345/${'staticImage.jpg'}`}} />
I have the following gulpfile
var gulp = require('gulp');
var clean = require('gulp-clean');
var rename = require('gulp-rename');
var coffee = require('gulp-coffee');
var cache = require('gulp-cached');
var path = require('path');
var dist = './Test/public/';
var assets = './Test/assets/';
var paths = {
coffee: ['./**/*.coffee']
};
var coffeeTask = function () {
console.log('coffeeTask');
return gulp.src(paths.coffee, { cwd: assets + '**' })
.pipe(cache('coffee'))
.pipe(coffee({ bare: true }))
.pipe(rename({
extname: ".coffee.js"
}))
.pipe(gulp.dest(dist));
};
gulp.task('clean', function() {
return gulp.src(dist)
.pipe(clean());
});
gulp.task('coffee', ['clean'], coffeeTask);
gulp.task('coffee-watch', coffeeTask);
gulp.task('build', ['clean', 'coffee']);
gulp.task('watch', ['build'], function() {
var w = gulp.watch(paths.coffee, ['coffee-watch']);
w.on('change', function(evt) {
console.log(evt);
});
});
gulp.task('default', ['build']);
The key point of this configuration is use the same tasks for deploy and watch processes (read "build" and "watch" tasks).
The problem is that watch task doesn't catche any new coffee files. Edited or removed coffee files are processed well. According the following issue it should works. What the reason is?
Solved by using gulp-watch module:
watch(paths.coffee, function(evt) {
gulp.start('coffee-watch');
});
The question no is how to remove in dist folder deleted file in assets folder?
I have two different paths where I want to compile the mobile vs desktop code. I would like to alternate by passing a grunt parameter in the command line.
/**
* #module Build
* #class Build.Config
* #static
*/
module.exports = function(grunt) {
var config = {};
var NewPath;
var env = grunt.option('target') || "Mobile";
if (env == "Desktop") { // MAKE THIS DYNAMIC WITH COMMAND LINE ARGUMENT
newPath = "source/desktop/";
}
else {
newPath = "source/mobile/";
}
config.root = newPath;
config.stylesheets = config.root + '/stylesheets';
config.javascripts = config.root + '/javascripts';
config.images = config.root + '/images';
config.jsbin = config.javascripts + '/generated';
config.cssbin = config.stylesheets + '/generated';
config.docsbin = 'docs';
// Project configuration.
grunt.initConfig({
'beautifier': {
'options': {
'indentSize': 1,
'indentChar': '\t',
'spaceAfterAnonFunction': true
}
},
'beautify': {
'files': [ config.javascripts + '/app/**/*.js' ]
},
'requirejs': require('./build/config/requirejs.js')(config),
'watch': require('./build/config/watch.js')(config),
'stylus':require('./build/config/stylus.js')(config)
});
// Default task.
grunt.registerTask('default', ['stylus:compile','requirejs']);
grunt.registerTask('dev', ['stylus:dev']);
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-stylus');
};
Turns out I was doing it right I just needed to pass in the variable for env correctly:
$ grunt --target="Desktop"
An alternate to --option is to pass it through the colon. for example passing it to jshint
grunt jshint:desktop
Then configure grunt to pick up that command line argument using process.argv and you can use it to configure your paths or whatever else might be needed:
module.exports = function(grunt) {
"use strict";
//dynamic config after the ':'. 'desktop' here
var env = process.argv[2].split(':')[1];
var config = {
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc',
"force": true
}
},
};
//...
config.jshint[env] = { // ex: $ grunt jshint:desktop
src: ['public/'+env+'/js/main.js']
};
//...
// Project configuration.
grunt.initConfig(config);
//...
};
One caveat on using process is that it won't work when you use a grunt task that respawns your process like the useful grunt-concurrent. In that case it's bettter to go with grunt.option as shown by #im_benton. passing grunt mytask --myvar=myval and picking it up in you Gruntfile.js as grunt.option('myvar') `