Grunt browser-sync not watching php file changes in Wordpress - wordpress

I've set up grunt successfully to watch sass and js file changes in my Gruntfile.js. The only thing its not picking up are the changes to my php files. Looking at the documentation for browser-sync for Wrodpress, i need to state options like so:
browserSync: {
files: {
src : [
'style.css',
'images/*',
'js/**/*.js',
'**/*.php'
],
},
options: {
// server: {
// host: "192.168.1.141:8888/bch",
// baseDir: "/", // "./",
// },
proxy: "localhost",
// port: 8888,
watchTask: true
}
}
I've tried the commented out options aswell as a slightly differnt sytax setup at http://www.browsersync.io/docs/grunt/ at the bottom of the page and for any option neither does the grunt-cli show any updates nor does the browser change on save. Is there an obvious component I'm missing?

For anyone fairly new to this as I am and wanted to know what i did:
browserSync: {
dev: {
options: {
proxy: "localhost:8888",
files: ['style.css', 'js/**/*.js', '**/*.php'],
watchTask: true,
}
}
}
Stating the port explicitly as per my quesiton example meant the browser sync wouldn't go to its default :3000 port for it to then run its sync magic
Although it does need a reference to the 8888 as its part of my base local URL. So instead i put it in the proxy: option and i can click through to any project from there in my htdocs folder.
Wrapping it in dev: {} to tell browser-sync i had my own server running (MAMP)
This also then stopped the annoying error of Fate Error: not running when trying to come out of the currently running 'grunt' command.
On Mac OSX Mavericks, with MAMP.

Related

Issue with react-refresh-webpack-plugin and wordpress/scripts using --hot

I am not able to get the HMR with "wp-scripts start --hot" running. I tried this in several project, including rather empty projects.
As soon as I add the --hot flag to my npm script, I can still get the script running but I get this error message in my console:
ReactRefreshEntry.js:17 Uncaught TypeError: Cannot read properties of undefined (reading 'injectIntoGlobalHook')
at ./node_modules/#pmmmwh/react-refresh-webpack-plugin/client/ReactRefreshEntry.js (ReactRefreshEntry.js:17:1)
at options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at startup:4:66
at __webpack_require__.O (chunk loaded:25:1)
at startup:9:1
at startup:9:1
It doesn't even load my Javascript as it seems to break at an earlier point.
I already changed Node Versions back and forth, deleted all node-modules and the package-lock.json, took out all my Javascript to see if this solves anything, but it doesn't.
My setup:
Local by Flyhweel as Wordpress local environment
Wordpress: 6.0.3
Node V 16.18.0
npm 8.19.2
#wordpress/scripts Version: 24.4.0
wp-config.php:
define('WP_DEBUG', false); define('SCRIPT_DEBUG', true);
Also I got the Gutenberg Plugin installed and activated as stated here: https://developer.wordpress.org/block-editor/reference-guides/packages/packages-scripts/#:~:text=%2D%2Dhot%20%E2%80%93%20enables%20%E2%80%9CFast%20Refresh%E2%80%9D.%20The%20page%20will%20automatically%20reload%20if%20you%20make%20changes%20to%20the%20code.%20For%20now%2C%20it%20requires%20that%20WordPress%20has%20the%20SCRIPT_DEBUG%20flag%20enabled%20and%20the%20Gutenberg%20plugin%20installed.
Does anyone else experience this bug or can anyone help with this?
Many thanks and cheers
Johannes
Alternative
I could not get react-refresh-webpack-plugin to work in #worpress/script so ended up using BrowserSyncPlugin, here is how i extended the #wordpress/script webpack config. Hope it helps someone
/**
* External Dependencies
*/
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
/**
* WordPress Dependencies
*/
const defaultConfig = require('#wordpress/scripts/config/webpack.config.js');
module.exports = {
...defaultConfig,
...{
entry: {
theme: path.resolve(process.cwd(), 'src', 'theme.js'),
},
plugins: [
...defaultConfig.plugins,
new BrowserSyncPlugin({
// inspect docker network to get this container external ip
// then specify it in host
host: '172.44.0.3', //docker container host
port: 8887,
//server: { baseDir: ['public'] },
proxy: 'http://172.44.0.1:7020/', //docker container host
open: false
}),
]
}
}
and yarn run start
Disclaimer: Am developing in docker env. i know its not answer to the question, but if you are stuck, kindly try it out.

Storybook build success but error when serving

I have encountered a problem when serving a built storybook. As you can see below, it shows only a spinner spinning into oblivion. When i opened the console, it says:
Error: manager received sharedStateChanged-manager-storybook/viewport but was unable to determine the source of the event
Here's my storybook configuration files:
main.js
module.exports = {
stories: [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
addons: [
"#storybook/addon-links",
"#storybook/addon-essentials",
"#storybook/preset-create-react-app"
],
webpackFinal: config => {
return {
...config,
plugins: config.plugins.filter(plugin => {
if (plugin.constructor.name === 'ESLintWebpackPlugin') {
return false
}
return true
}),
}
}
}
preview.js
import '../src/recore/.storybook/preview.css'
import * as Recore from '../src/recore'
Recore.init({
defaults: {
IMAGE_RESOLVER: path => {
return import('../src/assets/' + path)
}
}
})
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
}
To build the storybook, i run build-storybook -o ./build -s ./public -c .storybook
I am using npm, and it told me to do npm run build-storybook -- -o ... but it doesn't behave as expected. Also, I currently use "#storybook/react": "^6.1.21"
Has anyone encountered this problem before? Can you help me to fix it?
Many thanks before!
add "#storybook/builder-webpack5": "^6.2.9",
https://gist.github.com/shilman/8856ea1786dcd247139b47b270912324
When I had this problem I was starting the static file serving with npx serve -s.
Changing the startup to npx serve fixed the problem (this was hosting on a Linux web app in Azure).
Are you trying to deploy it to amplify?
If you are trying to deploy it to Amplify you need to rewrite some rules: (top to bottom)
1st rule: Source: /iframe.html Target: /iframe.html
2nd rule: Source: /<*> Target: /index.html
3rd rule: Source: </^[^.]+$|\.(?!(css|xml|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/> Target: /index.html
Be aware that the 1st rule the target is to iframe.html
I only needed 1 rule in my Amplify config to get storybook to work
Note the below is from terraform, but you should be able to grok it's meaning:
custom_rule {
source = "</^[^.]+$|\.(?!(html|css|gif|ico|jpg|js|png|txt|svg|woff|ttf)$)([^.]+$)/>"
status = "200"
target = "/index.html"
}
For AWS AMPLIFY
Source address: /iframe.html
Target address: /iframe.html
Type: 200 (Rewrite)
Source address: /<*>
Target address: /index.html
Type: 404 (Redirect)
Source address: </^[^.]+$|.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|woff2|ttf|map|json|xlsx)$)([^.]+$)/>
Target address: /index.html
Type: 200 (Rewrite)
how it should look

CSS loader error with webpack v3 after editing a webpack watched file in a server-side app

I am working on a node express api which is building a view via react and CSS modules (one CSS file within each component imported directly into the component). The react output is serialised with renderToStaticMarkup() which will be sent back to the requester in the JSON response. I also intend to send the compiled CSS in this response too.
I have a working build process via webpack which bundles my server app to one file. I am also currently bundling my CSS (modules) into one file (with the intention of reading this in later).
I am using webpack with its watch facility as follows (can't use webpack-dev-server as the api requires POST and there is no 'page' to update anyway):
cross-env NODE_ENV=development webpack -w --colors
My issue however is that whilst this all works fine on first compile, as soon as I change any file, I get a webpack error stating that I need an appropriate loader for the imported CSS file.
ERROR in ./src/app/components/Suggestions/Suggestions.css
Module parse failed: /home/me/myproject/src/app/components/Suggestions/Suggestions.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| .suggestions {
| background: blue;
| color: orange;
# ./src/app/components/Suggestions/Suggestions.js 11:19-47
# ./src/app/components/Suggestions/index.js
# ./src/server/middleware/buildSuggestions.js
# ./src/server/routes/index.js
# ./src/server/server.js
# multi babel-polyfill ./src/server/server.js
I have simplified my webpack config as much as possible and still get the issue. My simplified config (not extracting css to file and no PostCSS) is as follows:
webpack.config.babel.js
import path from 'path';
import nodeExternals from 'webpack-node-externals';
import PATHS from './config/paths';
// Host and port settings to spawn the dev server on
const HOST = 'localhost';
const PORT = 3000;
const LOCAL = `http://${HOST}:${PORT}`;
const DEV = process.env.NODE_ENV === 'development';
let serverConfig = {
entry: [
"babel-polyfill",
path.resolve(PATHS.src, 'server/server.js'),
],
output: {
filename: 'server.js',
path: PATHS.dist,
publicPath: '/'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: PATHS.src,
use: {
loader: 'babel-loader',
options: {
// babelrc at project root only for compiling this webpack
babelrc: false,
presets: [
'env',
'react'
],
plugins: [
'transform-object-rest-spread',
'syntax-dynamic-import',
'transform-class-properties',
]
}
}
},
{
test: /\.css$/,
use: [
{
loader : 'css-loader',
options: {
modules: true,
importLoaders: 1,
localIdentName: '[local]-[hash:base64]',
sourceMap: DEV
},
}
]
}
],
},
plugins: [
],
target: 'node',
externals: [nodeExternals()]
};
export default serverConfig;
So my question is, why does this work okay on first compile but not on a recompile after a change?
Stranger than fiction!
So I realised that if I run my build without the watcher...
cross-env NODE_ENV=development webpack --colors
and that process had ended, if I edited a file I still saw the error!!! Even though there was supposedly no watcher running. I left that terminal window alone with no running process, opened another terminal and edited a file within my src directory using vi (closed WebStorm in case it had some odd watcher running). Incredibly, the error popped up again in the original terminal window!!!
So it seems my issue was caused by a rogue webpack watch process that hadn't been killed properly. Couldn't find the process to manually kill it so had to do reboot. Literally hours lost on this bizzare issue. At least my whole build process is working again.

grunt-php task springing open multiple browser instances

I'm building a Gruntfile.js.
I'm trying to create tasks for responding to php requests.
Other tasks include live compiling compass/sass and live-reload.
I've hit an interesting snag:
When I start grunt, I can see in the terminal that the watch tasks is running, and that the php server is running: I get messages in terminal about certain files not being in place.
Now heres the thing... a couple of seconds after I start grunt, firefox windows start opening. (I start the task without firefox running at all. I generally use chromium and chrome).
New windows keep opening. ff messages about firefox crashing sometimes pop up. I also get windows popping up telling me that my ff profile is inaccessible - which is what I'd expect if I try and run 'firefox' from the terminal while ff is already running.
They keep popping up until I stop grunt from running. They all close immediately when I stop the task, by Ctrl-c from the terminal.
What could be causing this?
Here is my gruntfile
module.exports = function (grunt){
grunt.initConfig({
compass : {
dist : {
options : {
cssDir : 'css',
sassDir : 'sass',
debugInfo : true
}
}
},
php :{
dist : {
options : {
keepalive : true,
port: 9000
}
},
watch : {
files : ['*.html', '*.php', 'js/*', 'sass/*', 'css/*'],
tasks : ['compass'],
options : {
livereload: true
}
}
},
});
grunt.loadNpmTasks('grunt-php');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.registerTask('default', ['php', 'watch']) ;
} ;
Your watch task specifies that you want to use livereload - so, that's (kind of) expected, right?
See here:
https://github.com/gruntjs/grunt-contrib-watch#optionslivereload
http://livereload.com/

Run grunt server with various browsers

Is it possible to specify a particular browser (besides the OS' default) in the gruntfile or at the command prompt? E.g. "grunt server firefox" or the like. My default browser is Chrome, but I want to test/develop my site in multiple browsers. I am using GruntJS within Yeoman.
Bryan
Quick Answer
In Gruntfile.js you can add an app parameter:
open: {
server: {
url: 'http://localhost:<%= connect.options.port %>',
app: 'firefox'
}
},
Pull request: https://github.com/jsoverson/grunt-open/pull/7
Commit: https://github.com/GabLeRoux/grunt-open/commit/6f2c7069767e58160ec96aaaa8fa20ed210ba183
Command Line Parameters
It is possible to pass command line parameters in the app string, such as app: "chromium-browser --incognito" - #bk11425
From the documentation of grunt connect: https://github.com/gruntjs/grunt-contrib-connect
You can use:
open: {
target: 'http://localhost:8000', // target url to open
appName: 'open', // name of the app that opens, ie: open, start, xdg-open
callback: function() {} // called when the app has opened
}
i.e. appName: 'Google Chrome'
While the answers in here helped fix my occurrence of the problem, as someone who's not very familiar with grunt, I had a hard time figuring just exactly where I was supposed to put the "open:" stanza in my Gruntfile.js. It took me about three three tries for me to find the right spot (e.g I tried directly under 'grunt.initConfig' and under 'connect: options:' to no effect)
I'm using the Gruntfile.js as generated by the standard angular yeoman generator.
I'm posting where I put it in this file just to give a little more "context" for anyone in a similar predicament.
Here is the relevant snippet of the Gruntfile.js:
// ...
The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
//open: true, <- original line, comment out
// add this
open: {
//target: 'http://localhost:9000', <- this works too
target: 'http://localhost:<%= connect.options.port %>',
appName: 'firefox'
},
// end add
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
//...
The grunt server task has almost nothing to do with the browser, it just starts a static server for you to connect to and preview your app. You could theoretically use any browser you want to connect to http://localhost:8080/
To clarify based on the poster's comment:
grunt-open is a different task than grunt-server: https://npmjs.org/package/grunt-open.grunt-open uses node-open which just defaults to the default open task for darwin or start for win32: https://github.com/jjrdn/node-open#how-it-works
So, to answer, whatever application you have specified to open .html files (or whatever you're opening) will open with this task.

Resources