I have a gulp file that I have grabbed from here and modified to this:
var gulp = require('gulp'),
path = require('path'),
del = require('del'),
run = require('run-sequence'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
include = require('gulp-include'),
imagemin = require('gulp-imagemin'),
svgmin = require('gulp-svgmin'),
cache = require('gulp-cache'),
watch = require('gulp-watch'),
livereload = require('gulp-livereload')
//lr = require('tiny-lr'),
//server = lr()
;
var config = {
// Source Config
src : 'src', // Source Directory
src_assets : 'src/assets', // Source Assets Directory
src_fonts : 'src/assets/fonts', // Source Fonts Directory
src_images : 'src/assets/img', // Source Images Directory
src_javascripts : 'src/assets/js', // Source Javascripts Directory
src_stylesheets : 'src/assets/styles', // Source Styles Sheets Directory
src_main_scss : 'src/assets/styles/main.scss', // Source main.scss
src_main_js : 'src/assets/scripts/main.js', // Source main.js
// Destination Config
dist : 'dist', // Destination Directory
dist_assets : 'dist/assets', // Destination Assets Directory
dist_fonts : 'dist/assets/fonts', // Destination Fonts Directory
dist_images : 'dist/assets/img', // Destination Images Directory
dist_javascripts : 'dist/assets/js', // Destination Javascripts Directory
dist_stylesheets : 'dist/assets/css', // Destination Styles Sheets Directory
// Auto Prefixer
autoprefix : 'last 3 version' // Number of version Auto Prefixer to use
};
gulp.task('styles', function () {
return gulp.src(config.src_main_scss)
.pipe(sass({
outputStyle: 'expanded',
precision: 10,
sourceComments: 'none'
}))
.pipe(autoprefixer(config.autoprefix))
.pipe(gulp.dest(config.dist_stylesheets))
.pipe(livereload())
});
gulp.task('scripts', function () {
gulp.src(config.src_main_js)
.pipe(include())
.pipe(gulp.dest(config.dist_javascripts))
.pipe(livereload())
});
gulp.task('php', function() {
return gulp.src([path.join(config.src, '/**/*.php')])
.pipe(gulp.dest(config.dist))
.pipe(livereload())
});
gulp.task('images', function() {
gulp.src(path.join(config.src_images, '/**/*.png'))
.pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
.pipe(gulp.dest(config.dist_images))
});
gulp.task('svg', function() {
gulp.src(path.join(config.src_images, '/**/*.svg'))
.pipe(svgmin())
.pipe(gulp.dest(config.dist_images))
});
gulp.task('clean', function() {
del(path.join(config.dist, '/**/*'))
});
gulp.task('watch', function() {
//server.listen(35729, function (err) {
// if (err) {
// return console.log(err)
// };
gulp.watch(path.join(config.src_stylesheets, '/**/*.scss'), ['styles']);
gulp.watch(path.join(config.src_javascripts, '/**/*.js'), ['scripts']);
gulp.watch(path.join(config.src, '/**/*.php'), ['php']);
//});
});
gulp.task('default', function(cb) {
run('build', ['watch'], cb);
});
gulp.task('build', function (cb) {
run('clean', 'styles', 'scripts', 'php', 'images', 'svg', cb);
});
Now if I run 'gulp' everything works however when I go the my apache host the live reload is no longer working.
I am not that familiar with live reload so please walk me through any solutions.
I have installed live reload plugin and turned it on, still not working.
Am I missing a step with my host?
Alright, I don't know what this Gulpfile promised you in the first place, but I am missing two things here:
Any connection to your up-and-running server.
The place in your HTML file where you insert Livereload. Livereload needs to know where to be injected and just doesn't work automatically out of the box
This can be tricky, especially when you already have a server up and running, and it requires a lot of configuration. One tool which can be integrated with Gulp rather easily and does have a good Livereload setup out of the box is BrowserSync. You can just boot it up and create a proxy to any running server that you have. It will also take care of inserting the LiveReload snippet. I'd strongly suggest you switch to that one, especially if you are pretty new to that topic. I does just all for you :-)
I wrote about BrowserSync here, but here are the changes you would have to do to make it work:
Setup BrowserSync
Add this anywhere to your Gulpfile:
var browserSync = require('browser-sync');
browserSync({
proxy: 'localhost:80',
port: 8080,
open: true,
notify: false
});
(Don't forget to npm install --save-dev browser-sync first). This will create a new server, proxying your MAMP and injecting everything you need for LiveReload. Open your page at localhost:8080 (BrowserSync would do it for yourself), and you are ready to go
Add a reload-Call
Everywhere where you put livereload, change it to
.pipe(browserSync.reload({stream: true}))
Like this for example:
gulp.task('scripts', function () {
return gulp.src(config.src_main_js)
.pipe(include())
.pipe(gulp.dest(config.dist_javascripts))
.pipe(browserSync.reload({stream:true}))
});
This will trigger LiveReload and will refresh your sources. Make sure that you have it everywhere, where you change stuff.
Than you should be able to go. Good luck!
One more thing
Please write a little return statement before every gulp.src. This will let Gulp know that you are working with streams, making it a lot more able to work with streams.
Related
In my gulpfile.js I have the following code:
const themeName = "test"
const browsersync = require('browser-sync').create();
// Browsersync
function browserSyncServe(cb) {
browsersync.init({
proxy: `localhost/${themeName}/`,
notify: {
styles: {
top: 'auto',
bottom: '0',
},
},
});
cb();
}
function browserSyncReload(cb) {
browsersync.reload();
cb();
}
// Watch Task
function watchTask() {
watch('*.html', browserSyncReload);
watch('*.php', browserSyncReload);
watch(
['src/scss/**/*.scss', 'src/**/*.js'],
series(scssTask, jsTask, browserSyncReload)
);
}
// Default Gulp Task
exports.default = series(
browserSyncServe
);
It seems not so convinient to enter themeName for every single new project and match themeName with Wordpress theme folder name.
Is there any possibility to make it more automatic?
I'm trying to set up browser-sync together with Wordpress website on xampp.
Any help would be much appreciated!
I'm by no means an expert on Browsersync, but I am a WP and xampp user who got it to work perfectly with the following config:
browserSync( {
proxy: "https://localhost/mysite/",
https: {
key: "W:/xampp/htdocs/mkcert/localhost/localhost.key",
cert: "W:/xampp/htdocs/mkcert/localhost/localhost.crt"
}
});
NB: I am using xampp and it's installed on W:/ drive. I am also using mkcert for SSL.
You can learn more here.
......and I've no idea what the hell I'm doing. 😬
Okay let me explain I'm going back over a Wordpress course I did on Udemy where the now AWOL instructor implemented a automated workflow for us to use whereby anytime we typed PHP or JS the webpage would reload automatically, and it's working, actually it's working too fast for me. This time round for some reason it's driving me bonkers cos when I'm writing my code the page is recompiled before I can even finish typing a complete line of code! The webpage generates a parse error and I have to manually refresh the page when I'm done to clear the error as it doesn't get automatically refreshed due to the error, which sort of defeats the purpose of the automation.
The automated workflow was basically implemented by doing the following:
I've installed 2 files package.json & webpack.config.js into my theme
folder
Then I ran npm run devFast
Then by changing functions.php we got the WP theme to use the Node
generated assets. Node serves up all of the JavaScript and CSS within
one single bundled file, bundled.js
I've no idea where to start in asking for help with this so thought I'd start here. As I say any help with this would be appreciated even if you just signpost me. I'm also using Local by Flywheel to host the site locally and this has been a great tool.
If it helps my webpack file is ...
/*
SUPER IMPORTANT: This config assumes your theme folder is named
exactly 'fictional-university-theme' and that you have a folder
inside it named 'bundled-assets' - If you'd like to adapt this
config to work with your own custom folder structure and names
be sure to adjust the publicPath value on line #116. You do NOT
need to update any of the other publicPath settings in this file,
only the one on line #116.
*/
const currentTask = process.env.npm_lifecycle_event
const path = require("path")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const { CleanWebpackPlugin } = require("clean-webpack-plugin")
const ManifestPlugin = require("webpack-manifest-plugin")
const fse = require("fs-extra")
const postCSSPlugins = [require("postcss-import"), require("postcss-mixins"), require("postcss-simple-vars"), require("postcss-nested"), require("postcss-hexrgba"), require("postcss-color-function"), require("autoprefixer")]
class RunAfterCompile {
apply(compiler) {
compiler.hooks.done.tap("Update functions.php", function () {
// update functions php here
const manifest = fse.readJsonSync("./bundled-assets/manifest.json")
fse.readFile("./functions.php", "utf8", function (err, data) {
if (err) {
console.log(err)
}
const scriptsRegEx = new RegExp("/bundled-assets/scripts.+?'", "g")
const vendorsRegEx = new RegExp("/bundled-assets/vendors.+?'", "g")
const cssRegEx = new RegExp("/bundled-assets/styles.+?'", "g")
let result = data.replace(scriptsRegEx, `/bundled-assets/${manifest["scripts.js"]}'`).replace(vendorsRegEx, `/bundled-assets/${manifest["vendors~scripts.js"]}'`).replace(cssRegEx, `/bundled-assets/${manifest["scripts.css"]}'`)
fse.writeFile("./functions.php", result, "utf8", function (err) {
if (err) return console.log(err)
})
})
})
}
}
let cssConfig = {
test: /\.css$/i,
use: ["css-loader?url=false", { loader: "postcss-loader", options: { plugins: postCSSPlugins } }]
}
let config = {
entry: {
scripts: "./js/scripts.js"
},
plugins: [],
module: {
rules: [
cssConfig,
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-react", ["#babel/preset-env", { targets: { node: "12" } }]]
}
}
}
]
}
}
if (currentTask == "devFast") {
config.devtool = "source-map"
cssConfig.use.unshift("style-loader")
config.output = {
filename: "bundled.js",
publicPath: "http://localhost:3000/"
}
config.devServer = {
before: function (app, server) {
/*
If you want the browser to also perform a traditional refresh
after a save to a JS file you can modify the line directly
below this comment to look like this instead. I'm using this approach
instead of just disabling Hot Module Replacement beacuse this way our
CSS updates can still happen immediately without a page refresh.
If you're using a slower computer and the new bundle is not ready
by the time this is reloading the browser you can always just set the
"hot" property a few lines below this to false instead of true. That
will work on all computers and the only trade off is the browser will
perform a traditional refresh even for CSS changes as well.
*/
// server._watch(["./**/*.php", "./**/*.js"])
server._watch(["./**/*.php", "!./functions.php"])
},
public: "http://localhost:3000",
publicPath: "http://localhost:3000/",
disableHostCheck: true,
contentBase: path.join(__dirname),
contentBasePublicPath: "http://localhost:3000/",
hot: true,
port: 3000,
headers: {
"Access-Control-Allow-Origin": "*"
}
}
config.mode = "development"
}
if (currentTask == "build" || currentTask == "buildWatch") {
cssConfig.use.unshift(MiniCssExtractPlugin.loader)
postCSSPlugins.push(require("cssnano"))
config.output = {
publicPath: "/wp-content/themes/fictional-university-theme/bundled-assets/",
filename: "[name].[chunkhash].js",
chunkFilename: "[name].[chunkhash].js",
path: path.resolve(__dirname, "bundled-assets")
}
config.mode = "production"
config.optimization = {
splitChunks: { chunks: "all" }
}
config.plugins.push(new CleanWebpackPlugin(), new MiniCssExtractPlugin({ filename: "styles.[chunkhash].css" }), new ManifestPlugin({ publicPath: "" }), new RunAfterCompile())
}
module.exports = config
As already posted:
I should have said I'm using the auto-save feature in VS Code and to save my sanity I've turned this off which is doing the job. But is there another or better way?
I am having an issue where browsersync does not find/open my index.php file.
The relevant parts of my gulp file are as follows:
const browserSync = require("browser-sync").create();
const php = require('gulp-connect-php');
// Configure PHP server
gulp.task('php', function(){
php.server({base:'./', port:8010, keepalive:true});
});
// Inject php config into browserSync task
gulp.task('browserSync', function() {
browserSync.init({
proxy:'localhost:8000',
port: 8080,
baseDir: './',
open:true,
notify:false
});
});
// Watch files
function watchFiles() {
gulp.watch("./scss/**/*", css);
gulp.watch(["./js/**/*", "!./js/**/*.min.js"], js);
gulp.watch("./**/*.php", browserSync.reload);
gulp.watch("./**/*.html", browserSync.reload);
}
const watch = gulp.series(build, gulp.parallel(watchFiles, browserSync.reload));
// Export tasks
exports.watch = watch;
My console output when 'Gulp watch' is run looks like this:
The page never opens in the browser.
Any advice as to why it is getting hung up on browser-sync?
Also, browsersync works when run directly in the cmd with:
browser-sync start --proxy "localhost/BtcMiningContracts" --files "*.php, *.html, css/*.css, ./js/**/*"
thanks!
Many hours of searching have resulted in a working answer.
For anyone else experiencing the same issue, the updated code is below:
const browserSync = require("browser-sync");
const php = require('gulp-connect-php');
// Configure PHP server
gulp.task('connect-sync', function() {
php.server({}, function (){
browserSync({
proxy: '127.0.0.1:8000'
});
});
gulp.watch('**/*.php').on('change', function () {
browserSync.reload();
});
});
// Watch files
function watchFiles() {
gulp.watch("./scss/**/*", css);
gulp.watch(["./js/**/*", "!./js/**/*.min.js"], js);
gulp.watch("./**/*.php").on('change', function () {
browserSync.reload()});
}
This works with scss
hope it helps somebody out :)
I have setup a 2 custom tasks in my gulpfile.js :
var gulp = require('gulp'),
elixir = require('laravel-elixir');
gulp.task('task1', function() {
console.log('test1');
});
gulp.task('task2', function() {
console.log('test2');
});
elixir(function(mix) {
mix
.task('task1', './resources/**/*.php')
.task('task2', './resources/**/*.js')
;
});
When I run gulp watch I want only to see 'test1' when a *.php file is changed, and 'test2' when a *.js file is changed. But somehow both tasks are triggered when only 1 file changes.
Why is this happening ?
Is there a way to only trigger the right task ?
Have you tried this using Custom Watchers? See https://laravel.com/docs/5.2/elixir under "Custom Watchers".
new Task('task1', function() {
console.log('test1');
// gulp.src here ect.
})
.watch('./resources/**/*.php');
new Task('task2', function() {
console.log('test2');
// gulp.src here ect.
})
.watch('./resources/**/*.js');
This could fix your issue.
I'm trying Laravel Elixir and want to include bootstrap with includePaths but it does not work. Where am I going wrong?
var paths = {
'bootstrap': './vendor/bower_components/bootstrap-sass-official/assets/'
}
elixir(function(mix) {
mix.sass("style.scss", 'public/assets/css/', {includePaths: [paths.bootstrap + 'stylesheets/']})
});
I'm not sure if there is a reason that you want to do includePaths in your gulpfile, but for bootstrap you don't have to. The bootstrap include path is already configured out of the box in /node_modules/laravel-elixir/ingredients:
elixir.extend('sass', function(src, output, options) {
options = _.extend({
outputStyle: inProduction ? 'compressed' : 'nested',
includePaths: [elixir.config.bowerDir + "/bootstrap-sass-official/assets/stylesheets"]
}, options);
return compile({
compiler: 'Sass',
pluginName: 'sass',
pluginOptions: options,
src: src,
output: output,
search: '**/*.+(sass|scss)'
});
});
So all you should have to do is, in your gulpfile:
elixir(function(mix) {
mix.sass("style.scss");
});
And then in your style.scss:
#import "bootstrap";
I think you have to set your .bowerrc file to:
{
"directory": "vendor/bower_components"
}
but it looks like you have already done that.
I know this already has an accepted answer but I got something like this to work.
var paths = {
'bootstrap': '/bower_components/bootstrap-sass/assets/',
}
elixir(function (mix) {
mix.sass('app.scss', 'public/css', {
includePaths: [
__dirname + paths.bootstrap + 'stylesheets/'
]
});
mix.version("css/app.css");
});
Where bower_components is installed in the laravel root dir.
(From: https://laracasts.com/discuss/channels/requests/gulpfile-elixir-merge-scss-includepaths)
Another solution is using this line to compile sass or less files sitting in your vendor folder:
mix.less("../../../vendor/twbs/bootstrap/less/bootstrap.less");
Note: I used "composer require twbs/boostrap" to get the complete package. No bower needed.
Edit:
I output the compiled css file to the resource folder to combine it with other css files:
mix.less("../../../vendor/twbs/bootstrap/less/bootstrap.less", 'resources/css');
mix.styles([
"bootstrap.css"
], 'public/css/app.css');