va1 / browser-sync-webpack-plugin Goto Github PK
View Code? Open in Web Editor NEWEasily use BrowserSync in your Webpack project.
License: MIT License
Easily use BrowserSync in your Webpack project.
License: MIT License
I think is a good idea to move browser-sync to peerDependencies to keep track of automatic updates in the module
// test.js
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
$ node test.js
Plugin.prototype.apply = function (compiler) {
ReferenceError: Plugin is not defined
[email protected]
is not working, but @1.0.2
is no probrem.
node : 5.7.1
webpack : ^1.13.1
browser-sync : ^2.12.10
Hi there! Thanks for this good plugin. I have a question about it.
I recently found out that webpack can't reload browser when I changed html file, and save HMR reloading for JS.
I think It can be reached with your plugin. We would write to watch html files for browser sync.
So reloading of JS, CSS is job for HMR, reloading of HTML is job for browser sync plugin.
Could we do that ??
Thanks, Max
any chance of using this with electron?.. it doesnt server the files... electron does get those files from the localhost:3000 however the little snippet injected into browsers doesnt get injected into electron... causing it to not refresh automatically... so pretty much i can only see anything on browsers..
This could be useful for contributors to test any changes (manually for now) inside the repo, not having to use an external environment.
This folder should be in .npmignore.
Automated testing I think is out of the scope of this project since it's more of a wrapper plugin for Browsersync.
Perhaps some unit tests for the css emissions check?
I'm trying to setup bs-fullscreen-message
browser sync plugin with this webpack plugins, but it looks that doesn't work.
Any tip about how to setup correctly?
Related: https://github.com/shakyShane/bs-fullscreen-message#usage
I have config
....
new BrowserSyncPlugin({
notify: false,
port: 8080,
proxy: 'http://' + host + ':' + 3001 + '/',
}, {
reload: false,
}),
but if I change *.html files, I want reload page
Not a major issue, just something that I noticed. It appears that when I start up webpack, browsersync ignores the host setting in the BrowserSyncPlugin and instead opens a new tab in my internet browser at: localhost:4200 (note it doesn't appear to ignore the port).
sample config:
new BrowserSyncPlugin({
host: 'local.example.com',
port: 4200,
proxy: 'http://local.example.com:3000/'
})
Hi, i set proxy
in Webpack-dev-server as below
devServer: {
port: METADATA.port,
host: METADATA.host,
proxy: {
"/service_detail/*": {
target:"http://localhost:3004",
secure: false
}
}
}
My app is running on http://localhost:3000/ (Webpack-dev-server)
when i click some button on my app UI
The AJAX GET ( http://localhost:3000/service_detail ) will be fired
and Webpack-dev-server will proxy that url to json-server
that's, the process of that AJAX GET like below
(From my app)
http://localhost:3000/service_detail
|
V
Webpack-dev-server
|
V
(To json-server)
http://localhost:3004/service_detail
everything is working as expected
then i integrate the browser-sync-webpack-plugin ...
new BrowserSyncPlugin(
// BrowserSync options
{
host: 'localhost',
port: 3002,
proxy: 'http://localhost:3000',
},
// plugin options
{
reload: true
}
)
so now i can see my app running on http://localhost:3002/ (BrowserSync)
and i can see that in my mobile by typing <my ip>:3002
in url address bar
looks great !!!
If now i click that button (no matter where i do that in my mobile or pc)
I find out the app cant fetch the result from json-server in my mobile !!!
but in my pc, it still works expected
WHY ?
Is it a bug or i miss some concept of it ?
How can i check browser sync already running if i am using this plugin.
give me a warn with webpack 2.0
[email protected] requires a peer of webpack@^1.9.0 but none was installed.
:)
[HMR] logs are polluting my console. Can we setup webpack-hot-middleware settings like noInfo: true
Fail, code block hitting in. It is handled within my webpack config file.
Hey,
Can you please add support for the latests webpack builds?
Best
Hi,
I'm using this browser-sync-webpack-plugin
(along with gulp+webpack-dev-server) to run an Angular application built with Angular CLI.
The plugin config is the same as default:
module.exports = {
// ...
plugins: [
new BrowserSyncPlugin(
// BrowserSync options
{
// browse to http://localhost:3000/ during development
host: 'localhost',
port: 3000,
// proxy the Webpack Dev Server endpoint
// (which should be serving on http://localhost:3100/)
// through BrowserSync
proxy: 'http://localhost:3100/'
},
// plugin options
{
// prevent BrowserSync from reloading the page
// and let Webpack Dev Server take care of this
reload: false
}
)
]
}
Almost everything works pretty well. BrowserSync
proxies to webpack-dev-server
, its features like scroll synchronization, CSS outlines, CSS grids, work great across browsers/devices (tested with Chrome, Chrome Android and Firefox).
The plugin DOES detect changes from webpack-dev-server
, and refresh the page on PC browsers.
But the refresh is not triggered automatically on my mobile browser (Chrome Android v.57.0.2950.3).
even if the "Rebuilding..." message is correctly displayed.
Any ideas?
Thanks in advance
Here is my gulpfile:
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import del from 'del';
import source from 'vinyl-source-stream';
import runSequence from 'run-sequence';
import {reload} from 'browser-sync';
import historyApiFallback from 'connect-history-api-fallback';
import webpack from 'webpack-stream';
import BrowserSyncPlugin from 'browser-sync-webpack-plugin';
const AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
];
const $ = gulpLoadPlugins()
, env = 'dev';
global.isWatching = false;
gulp.task('clean:dev', del.bind(null, ['.tmp'], {dot: true}));
gulp.task('clean:dist', del.bind(null, ['dist'], {dot: true}));
gulp.task('webpack', () => {
return gulp.src('./app/scripts/app.jsx')
.pipe(webpack({
node: {
net: "empty",
dns: "empty"
},
debug: true,
devtool: 'source-map',
watch: true,
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel-loader?stage=0', exclude: /node_modules/ }
]
},
output: {
filename: "bundle.js"
},
resolve: {
modulesDirectories: [
'node_modules',
'app/scripts'
],
extensions: [ "", '.js', '.jsx' ]
},
plugins: [
new BrowserSyncPlugin({
port: 8000,
open: false,
minify: false,
host: "127.0.0.1",
server: {
baseDir: ["app", ".tmp"],
middleware: [ historyApiFallback() ]
}
})
]
}))
.pipe(gulp.dest('.tmp/scripts/'))
.pipe(reload({stream: true}));
});
gulp.task('imagemin', () => {
return gulp.src('app/images/*')
.pipe($.imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}]
}))
.pipe(gulp.dest('dist/images'));
});
gulp.task('copy', () => {
return gulp.src(['app/*.txt', 'app/*.ico'])
.pipe(gulp.dest('dist'));
});
gulp.task('bundle', ['webpack'], () => {
const assets = $.useref.assets();
const jsFilter = $.filter(['**/*.js']);
const htmlFilter = $.filter(['*.html']);
return gulp.src('app/*.html')
.pipe(assets)
.pipe($.rev())
.pipe(jsFilter)
.pipe($.uglify({mangle: false}))
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe($.autoprefixer({
browsers: ['last 5 versions']
}))
.pipe(cssFilter.restore())
.pipe(assets.restore())
.pipe($.useref())
.pipe($.revReplace())
.pipe(gulp.dest('dist'))
.pipe($.size());
});
gulp.task('sass', () => {
return gulp.src([
'app/scss/all.scss'
])
.pipe($.sourcemaps.init())
.pipe($.sass({
precision: 10
}).on('error', $.sass.logError))
.pipe($.cssInlineImages({
webRoot: 'app/scss/mdl/'
}))
.pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
//.pipe($.if('*.css', $.csso()))
//.pipe($.concat('all.min.css'))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest('.tmp/css'))
.pipe(reload({stream: true}))
.pipe($.size({title: 'styles'}));
});
gulp.task('setWatch', () => {
global.isWatching = true;
});
gulp.task('watch', ['setWatch'], () => {
gulp.watch("app/scss/**/*.scss", ['sass']);
gulp.watch(['app/*.html'], reload);
});
gulp.task('csscomb', function() {
return gulp.src('app/scss/app.scss')
.pipe($.csscomb())
.pipe(gulp.dest('app/scss'))
});
gulp.task('serve', ['clean:dev'], () => {
runSequence(
['webpack', 'watch', 'sass']
)
});
gulp.task('build', ['clean:dev', 'clean:dist'], () => {
runSequence(
['webpack', 'imagemin', 'copy', 'bundle']
)
});
gulp.task('default', ['serve']);
Browsersync starts, but it doesn't inject CSS, the page just reloads.
Did I do smth wrong?
Hello, I'm literally 2 hours into learning how to use Webpack. I'm trying to move away from using Gulp. I found your plugin and all is good. My one thing is trying to get my html file to reload the page when I edit and save them. I tried adding the index.html file name to the entry property in the array but that only seems to work when I save the main.js file. Only then will my index.html file show its new edits.
Do you have any advice on what I should do?
My webpack.config.js file:
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
entry: ['index.html', './main.js'],
output: {
path: __dirname,
filename: 'bundle.js'
},
plugins: [
new BrowserSyncPlugin({
// browse to http://localhost:3000/ during development,
// ./public directory is being served
host: 'localhost',
port: 3000,
server: { baseDir: ['./'] }
})
]
}
Hi,
Do you know if i can cancel webpack server for creat new proxy ? (for example, proxy my local server) :
new BrowserSyncPlugin(
{
proxy: 'my-dev.lan',
port: 8080,
open: true,
watchTask: true
}
)
Thank you !
Hi, I'm currently running this plugin in Browsersync proxy mode, alongside the webpack-dev-middleware express middleware, it's working really well. One drawback, however, is that I'm running the express server with nodemon, and automatically restarting the express server when I make server-side changes. This causes the Browsersync instance to tear down and start up again, with each server restart (which adds some overhead).
I was attempting to run the Browsersync server outside of the express app (within gulp for instance), and use ths plugin (or the webpack-dev-middleware) to trigger a Browsersync reload, but I can't get a handle to the browsersync instance from within the express app (since it's created/running from gulp). I know this isn't the intent of this plugin, but was wondering if you've experienced anything similar?
Thanks again for the plugin.
I'M using Browser Sync with webpack-dev-server, And facing the issue while using browser sync..!! only form fill up is working, click, scroll is not working in browser sync, and there is no any compile time error occurring, But above things are not working..!! Here is my "Webpack.dev.js" file, So what is wrong over here..?
const helpers = require('./helpers');
const buildUtils = require('./build-utils');
const webpackMerge = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const EvalSourceMapDevToolPlugin = require('webpack/lib/EvalSourceMapDevToolPlugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = function (options) {
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3000;
const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, {
host: HOST,
port: PORT,
ENV: ENV,
HMR: helpers.hasProcessFlag('hot'),
PUBLIC: process.env.PUBLIC_DEV || HOST + ':' + PORT
});
return webpackMerge(commonConfig({ env: ENV, metadata: METADATA }), {
output: {
path: helpers.root('dist'),
filename: '[name].bundle.js',
sourceMapFilename: '[file].map',
chunkFilename: '[id].chunk.js',
library: 'ac_[name]',
libraryTarget: 'var',
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
include: [helpers.root('src', 'styles')]
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
include: [helpers.root('src', 'styles')]
},
]
},
plugins: [
new EvalSourceMapDevToolPlugin({
moduleFilenameTemplate: '[resource-path]',
sourceRoot: 'webpack:///'
}),
new NamedModulesPlugin(),
new LoaderOptionsPlugin({
debug: true,
options: { }
}),
new BrowserSyncPlugin({
// browse to http://localhost:3000/ during development,
host: 'localhost',
port: 4000,
proxy: 'http://localhost:3000'
},
{
reload: false
})
],
devServer: {
port: METADATA.port,
host: METADATA.host,
hot: METADATA.HMR,
public: METADATA.PUBLIC,
historyApiFallback: true,
watchOptions: {
ignored: /node_modules/
},
setup: function(app) {
// For example, to define custom handlers for some paths:
// app.get('/some/path', function(req, res) {
// res.json({ custom: 'response' });
// });
},
},
node: {
global: true,
crypto: 'empty',
process: true,
module: false,
clearImmediate: false,
setImmediate: false,
fs: 'empty'
}
});
};
i just installl and require it
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
error shows:
$ Error: Cannot find module 'xmlhttprequest'
....
I've created a new app using VS Code and the dotnet CLI:
dotnet new angular
I've added code from the GitHub page:
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
// ...
plugins: [
new BrowserSyncPlugin(
// BrowserSync options
{
// browse to http://localhost:3000/ during development
host: 'localhost',
port: 3000,
// proxy the Webpack Dev Server endpoint
// (which should be serving on http://localhost:3100/)
// through BrowserSync
proxy: 'http://localhost:3100/'
},
// plugin options
{
// prevent BrowserSync from reloading the page
// and let Webpack Dev Server take care of this
reload: false
}
)
]
Upon executing the command, 'dotnet run', a browser opens but the page never loads.
the new version 2.0.0 throws an error when running webpack --watch
(function (exports, require, module, __filename, __dirname) { const { extend, isFunction } = require('lodash')
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Module.require (module.js:367:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/ninaregli/vagrant-local/www/cofi/public_html/wp-content/themes/cofi/node_modules/browser-sync-webpack-plugin/index.js:1:89)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)`
Version 1.1.4 seems to work fine. These are my dependencies in my package.json file:
"devDependencies": {
"browser-sync": "^2.23.6",
"browser-sync-webpack-plugin": "^1.1.4",
"css-loader": "^0.28.9",
"extract-text-webpack-plugin": "^3.0.2",
"lodash": "^4.17.5",
"node-sass": "^4.7.2",
"postcss-loader": "^2.1.0",
"sass-loader": "^6.0.6",
"style-loader": "^0.20.1",
"uglifyjs-webpack-plugin": "^1.1.8",
"webpack": "^3.10.0"
},
Hey,
I'm trying to proxy a wordpress server in my browsersync configuration. Everything almost works but browser sync reloads before the webpack build is finished. If I make a change, then save the file, the browser refreshes and I see the old content. If I save again (or manually refresh), the browser will refresh and show the changes. Here's my webpack configuration.
var debug = process.env.NODE_ENV !== 'production';
var webpack = require('webpack');
var path = require('path');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
var webpackSettings = {
context: path.join(__dirname, 'src'),
devtool: debug ? "inline-sourcemap" : null,
entry: './scripts/main.jsx',
output: {
path: __dirname + '/dist/scripts/',
filename: 'main.min.js'
},
plugins: debug ? [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.NoErrorsPlugin(),
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
proxy: 'http://local.php.server.address/'
})
] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
resolve: {
extensions: ['', '.js', '.jsx', ]
},
debug: debug,
module: {
loaders: [{
test: /\.jsx?/,
exclude: /(node_modules|bower_components)/,
loaders: ['babel?presets[]=react,presets[]=es2015'],
},
{
test: /\.scss$/,
loaders: [ 'style', 'css?sourceMap', 'sass?sourceMap' ]
}],
}
};
module.exports = webpackSettings
and I execute using webpack --watch
apologies if this is outside of the scope of this plugin.
Thanks!
* edit: clarified issue
Hey there, everything works so far expect it i try to connect from a mobile network device, it wont load the js injected css. I tried everything from changing the proxy, public path etc. i am using valet, maybe someone achieved to get it working...this is my config:
import path from 'path';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import BrowserSyncPlugin from 'browser-sync-webpack-plugin';
module.exports = {
entry: {
'app.bundle': './src/scripts/index.js'
},
cache: true,
output: {
filename: '[name].js',
publicPath: 'http://0.0.0.0:8080/',
chunkFilename: '[chunkhash].js',
},
devServer: {
hot: true,
inline: true,
overlay: false,
quiet: true,
contentBase: path.resolve(__dirname, ./src/templates/'),
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
},
watchContentBase: true,
watchOptions: {
poll: false, // might be needed for homestead/vagrant setup, review
},
historyApiFallback: false,
noInfo: true,
},
performance: {
hints: false,
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
inject: true,
alwaysWriteToDisk: true,
}),
new BrowserSyncPlugin(
// BrowserSync options
{
host: 'localhost',
port: 3000,
proxy: 'https://app.dev',
},
// plugin options
{
// prevent BrowserSync from reloding the page
// and let Webpack Dev Server take care of this
reload: false,
},
),
],
};
Release tags would help the community using this repo future proof their projects.
I am no expert but when I previously used the @2.0.1 version, adding the plugin to webpack worked, but when the new version is added, even the webpack server will not output to the browser.
Hi!
I can't seem to get CSS injections working - it just keeps refreshing the page.
Hi,
I am running webpack on a very new chromebook that prefers IPv6 strongly to IPv4. When I start my webpack/browser-sync with the following config
var customer = process.env.customer;
var commonConfig = require('./webpack.common.js');
var customerUrl = require('./customerUrls.json');
var webpackMerge = require('webpack-merge');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = webpackMerge(commonConfig, {
plugins: [
new BrowserSyncPlugin({
host: "[::1]",
port: 3000,
proxy: customerUrl[customer],
serveStatic: ["./build/" + customer, "./src/"],
snippetOptions: {
rule: {
async: false,
match: /<\/head>/i,
fn: function(snippet, match) {
var file = "<script async type='text/javascript' src='/bundle.js' />";
return file + snippet + match
}
}
}
},
{
reload: true
})
]
});
I get the mostly correct output on my dev console, it looks like
[Browsersync] Access URLs:
----------------------------------
Local: http://localhost:3000
External: http://[::1]:3000
----------------------------------
UI: http://localhost:3001
UI External: http://::1:3001
----------------------------------
I am new to webpack and browser-sync world, I haven't found the toggle that would try to autopop the site I am proxying at
http://[::1]:3000
rather than
http://localhost:3000
I've mucked with etc hosts to no avail yet, I am sure I am overlooking some really simple. Help is appreciated!
For what it is worth: ipv6 may be a culprit too in issue #27 for the person who spoke of works on older host but not newer one.
Hey there i am trying to set it up working with HMR and valet as a proxy, but webpack throws out :
Error
/Users/hendrik/Documents/Github/Projects/app/node_modules/webpack-dev-middleware/lib/Shared.js:216
context.compiler.plugin("done", share.compilerDone);
^
TypeError: context.compiler.plugin is not a function
at Shared (/Users/hendrik/Documents/Github/Projects/Hajok/node_modules/webpack-dev-middleware/lib/Shared.js:216:19)
at module.exports (/Users/hendrik/Documents/Github/Projects/Hajok/node_modules/webpack-dev-middleware/middleware.js:22:15)
at Object.<anonymous> (/Users/hendrik/Documents/Github/Projects/Hajok/webpack.config.js:87:9)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
(beside that i can't get webpack-dev-server
working with valet and proxy, it doesn't serve files from the memory, maybe someone knows why, browser-sync-webpack-plugin
works fine though)
After I start browser sync through webpack with your plugin, in another file I try to get it like this:
var bs = require('browser-sync').get('bs-webpack-plugin');
but I get an error An instance with the name
bs-webpack-pluginwas not found.
.
Does this work for you? Thanks.
Recent update to index.js is throwing errors. The function name was updated but the prototype references and export object were not updated to match.
Hi
I can't get it to work - and I actually don't see how it possible since webpack serves from memory and not the file system.
Webpack serves well on localhost:8080
but BrowserSyncPlugin on localhost:3000
returns 404.
This is the config I use with BUILD = false
and TEST = false
:
// Modules
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = function makeWebpackConfig (options) {
/**
* Environment type
* BUILD is for generating minified builds
* TEST is for generating test builds
*/
var BUILD = !!options.BUILD;
var TEST = !!options.TEST;
/**
* Config
* Reference: http://webpack.github.io/docs/configuration.html
* This is the object where all configuration gets set
*/
var config = {};
/**
* Entry
* Reference: http://webpack.github.io/docs/configuration.html#entry
* Should be an empty object if it's generating a test build
* Karma will set this when it's a test build
*/
if (TEST) {
config.entry = {}
} else {
config.entry = {
app: './src/app.js'
}
}
/**
* Output
* Reference: http://webpack.github.io/docs/configuration.html#output
* Should be an empty object if it's generating a test build
* Karma will handle setting it up for you when it's a test build
*/
if (TEST) {
config.output = {}
} else {
config.output = {
// Absolute output directory
path: __dirname + '/public',
// Output path from the view of the page
// Uses webpack-dev-server in development
publicPath: BUILD ? '/' : 'http://localhost:8080/',
// Filename for entry points
// Only adds hash in build mode
filename: BUILD ? '[name].[hash].js' : '[name].bundle.js',
// Filename for non-entry points
// Only adds hash in build mode
chunkFilename: BUILD ? '[name].[hash].js' : '[name].bundle.js'
}
}
/**
* Devtool
* Reference: http://webpack.github.io/docs/configuration.html#devtool
* Type of sourcemap to use per build type
*/
if (TEST) {
config.devtool = 'inline-source-map';
} else if (BUILD) {
config.devtool = 'source-map';
} else {
config.devtool = 'source-map'; //'eval';
}
/**
* Loaders
* Reference: http://webpack.github.io/docs/configuration.html#module-loaders
* List: http://webpack.github.io/docs/list-of-loaders.html
* This handles most of the magic responsible for converting modules
*/
// Initialize module
config.module = {
preLoaders: [],
loaders: [{
// JS LOADER
// Reference: https://github.com/babel/babel-loader
// Transpile .js files using babel-loader
// Compiles ES6 and ES7 into ES5 code
test: /\.js$/,
loader: 'babel',
exclude: /(node_modules|bower_components)/
}, {
// ASSET LOADER
// Reference: https://github.com/webpack/file-loader
// Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
// Rename the file using the asset hash
// Pass along the updated reference to your code
// You can add here any file extension you want to get copied to your output
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
loader: 'file'
}, {
// HTML LOADER
// Reference: https://github.com/webpack/raw-loader
// Allow loading html through js
test: /\.html$/,
loader: 'raw'
}]
};
// ISPARTA LOADER
// Reference: https://github.com/ColCh/isparta-instrumenter-loader
// Instrument JS files with Isparta for subsequent code coverage reporting
// Skips node_modules and files that end with .test.js
if (TEST) {
config.module.preLoaders.push({
test: /\.js$/,
exclude: [
/(node_modules|bower_components)/,
/\.test\.js$/
],
loader: 'isparta-instrumenter'
})
}
// CSS LOADER
// Reference: https://github.com/webpack/css-loader
// Allow loading css through js
//
// Reference: https://github.com/postcss/postcss-loader
// Postprocess your css with PostCSS plugins
var cssLoader = {
test: /\.css$/,
// Reference: https://github.com/webpack/extract-text-webpack-plugin
// Extract css files in production builds
//
// Reference: https://github.com/webpack/style-loader
// Use style-loader in development for hot-loading
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss')
};
// Skip loading css in test mode
if (TEST) {
// Reference: https://github.com/webpack/null-loader
// Return an empty module
cssLoader.loader = 'null'
}
// Add cssLoader to the loader list
config.module.loaders.push(cssLoader);
/**
* PostCSS
* Reference: https://github.com/postcss/autoprefixer-core
* Add vendor prefixes to your css
*/
config.postcss = [
autoprefixer({
browsers: ['last 2 version']
})
];
/**
* Plugins
* Reference: http://webpack.github.io/docs/configuration.html#plugins
* List: http://webpack.github.io/docs/list-of-plugins.html
*/
config.plugins = [
// Reference: https://github.com/webpack/extract-text-webpack-plugin
// Extract css files
// Disabled when in test mode or not in build mode
new ExtractTextPlugin('[name].[hash].css', {
disable: !BUILD || TEST
})
];
// Skip rendering index.html in test mode
if (!TEST) {
// Reference: https://github.com/ampedandwired/html-webpack-plugin
// Render index.html
config.plugins.push(
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body'
})
)
}
// Add build specific plugins
if (BUILD) {
config.plugins.push(
// Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
// Only emit files when there are no errors
new webpack.NoErrorsPlugin(),
// Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
// Dedupe modules in the output
new webpack.optimize.DedupePlugin(),
// Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
// Minify all javascript, switch loaders to minimizing mode
new webpack.optimize.UglifyJsPlugin()
)
}
// Add dev specific plugins
if (!TEST && !BUILD) {
config.plugins.push(
// Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
// Only emit files when there are no errors
new BrowserSyncPlugin({
host: 'localhost',
port: 3000,
server: { baseDir: ['public'] }
})
)
}
/**
* Dev server configuration
* Reference: http://webpack.github.io/docs/configuration.html#devserver
* Reference: http://webpack.github.io/docs/webpack-dev-server.html
*/
config.devServer = {
contentBase: './public',
stats: {
modules: false,
cached: false,
colors: true,
chunk: false
}
};
return config;
};
Using the configuration below is it possible to have browser-sync open the browser to the host and port instead of defaulting to localhost and port. A few of our projects have OAuth set to be 127.0.0.1 so we can't use localhost to authenticate.
new BrowserSyncPlugin(
{
host: 'http://127.0.0.1',
port: 8888,
proxy: 'http://127.0.0.1:8080'
}
)
There are 9 releases on NPM, and none of them have associated tags in git. I did some quick looking through the commit history and I think this is where the versions on NPM line up:
This plugin may soon have issues, since the way the plugins are written has changed substantially:
See: Breaking changes for plugins/loaders
https://github.com/webpack/webpack/releases/tag/v4.0.0-beta.0
I've found this issue with a build 2 days ago, and never happen before.
ReferenceError: Plugin is not defined at Object.<anonymous> ((...)/node_modules/browser-sync-webpack-plugin/index.js:21:1) at Module._compile (module.js:413:34) at Object.Module._extensions..js (module.js:422:10) at Module.load (module.js:357:32) at Function.Module._load (module.js:314:12) at Module.require (module.js:367:17) at require (internal/module.js:16:19) at Object.<anonymous> ((...)/webpack.config.js:2:25) at Module._compile (module.js:413:34) at Object.Module._extensions..js (module.js:422:10)
I'm using the following code in webpack.config.js
plugins: [ new BrowserSyncPlugin({ host: 'localhost', port: 3000, proxy: 'localhost:4000' }) ]
Also my co worker mentioned the sync stop working altogether in his machine, but mine still works as normal.
I don't know if this is related to this plugin specifically or with Webpack/Browser Sync in general.
p.s. found out that someone else had the same issue in Stackoverflow:
http://stackoverflow.com/questions/37628622/webpack-and-browsersync-plugin-not-defined
Edit: Wrong plugin (browsersync-webpack-plugin
instead browser-sync-webpack-plugin
).
I am trying to use browser-sync-webpack-plugin with the following config,
var path = require('path');
var webpack = require("webpack");
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
module.exports = {
entry: ['./src/index.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new UglifyJSPlugin(),
new BrowserSyncPlugin({
host: 'localhost',
port: 4000,
proxy: 'http://localhost:3000'
},
// plugin options
{
// prevent BrowserSync from reloading the page
// and let Webpack Dev Server take care of this
reload: false
})
]
};
Behavior:
Browser-sync output shows up fine after using webpack --watch
and it launches localhost:4000 in chrome as expected, but nothing ever loads. It sits on 'connecting...' forever.
Expected Behavior:
Browser-sync works.
The express server is running fine on localhost:3000. I have tried different permutations of these options, but these are the defaults aside from port changes from the guide.
Using browser-sync (CLI) by itself works fine. I am able to use bs on my express server to sync file changes.
We are having a warning from browser-sync-webpack-plugin
after upgrade to webpack 3, do you want to add webpack 3 in your peer dependencies ?
Keep in mind, per your instructions on npm and here, it wont always be webpack.config.js
in my case its webpack.mix.js
. This threw me off, i started looking into if i needed to add the config, or override it, and where it might reside, all along i finally realized it was where i was initiating it in my webpack.mix.js
mix.webpackConfig({
plugins: [
new BrowserSyncPlugin({
port: 3009,
files: [
'app/**/*',
'public/**/*',
'resources/views/**/*',
'resources/assets/**/*',
'routes/**/*'
]
})
]
}) ;
For some reason, i had to override the port, node is showing up several times in netstat, i use msys2 (xming or cygwin), thats how i came across this.
Thanks.
I want to disable the automatic browser tab and UI, but this doesn't work:
new BrowserSyncPlugin(
{
host: 'localhost',
port: 3000,
proxy: 'http://localhost:8080/'
},
{
reload: false,
open: false,
ui: false
}
)
The plugin does not reload my browser all the time. When I change the (S)CSS or .TWIG/HTML browsersync is very inconsistent in reloading the browser. Sometimes I need to save my files multiple times to see the changes. I already tried to put the delay-option on, disabled all the unnecessary plugins, but without luck.
Package.json:
"name": "Test",
"version": "1.0.0",
"description": "Test website",
"scripts": {
"watch": "cross-env NODE_ENV=development webpack --progress --hide-modules --watch",
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
},
"main": "index.js",
"author": "Teun",
"license": "MIT",
"dependencies": {
"fontfaceobserver": "^2.0.9",
"lost": "^8.0.0",
"vue": "^2.3.3"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"browser-sync": "^2.18.12",
"browser-sync-webpack-plugin": "^1.1.4",
"clean-webpack-plugin": "^0.1.16",
"cross-env": "^5.0.0",
"css-loader": "^0.28.1",
"eslint": "^3.19.0",
"eslint-loader": "^1.7.1",
"extract-text-webpack-plugin": "^2.1.0",
"file-loader": "^0.11.1",
"img-loader": "^2.0.0",
"node-sass": "^4.5.3",
"path": "^0.12.7",
"postcss-cssnext": "^2.11.0",
"postcss-import": "^10.0.0",
"postcss-loader": "^2.0.5",
"resolve-url-loader": "^2.0.2",
"sass-loader": "^6.0.5",
"style-loader": "^0.17.0",
"stylelint-config-lost": "^0.0.3",
"stylelint-config-standard": "^16.0.0",
"stylelint-webpack-plugin": "^0.7.0",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5",
"webpack-manifest-plugin": "^1.1.0",
"webpack-merge": "^4.1.0"
}
}
Webpack config
const path = require('path');
const ManifestPlugin = require('webpack-manifest-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StylelintPlugin = require('stylelint-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const merge = require('webpack-merge');
const env = process.env.NODE_ENV;
// Change paths here, not in config objects below
const PATHCONFIG = {
SRC_ROOT: path.resolve(__dirname, 'src'),
BUILD_ROOT: path.resolve(__dirname, 'public/dist'),
BUILD_IMAGES: './template-images',
PROXY_ADDRESS: 'http://test.dev'
};
const commonConfig = merge([
{
entry: {
app: [
`${PATHCONFIG.SRC_ROOT}/js/app.js`,
`${PATHCONFIG.SRC_ROOT}/scss/app.scss`
]
},
output: {
filename: '[name].js',
path: `${PATHCONFIG.BUILD_ROOT}`
},
module: {
rules: [
// JS
{
test: /\.js$/,
exclude: '/node-modules',
loader: "babel-loader"
},
// IMAGES with optimizer for every described format (runs in production only)
{
test: /\.(jpe?g|png|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: `${PATHCONFIG.BUILD_IMAGES}/[name].[ext]`
}
},
{
loader: 'img-loader', // Default settings for image optimization/minification. Check https://github.com/thetalecrafter/img-loader for config
options: {
enabled: (env === 'production')
}
}
]
},
// Fonts
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader?name=fonts/[name].[ext]'
]
},
// CSS/SCSS
{
test: /\.s?css$/,
use: ExtractTextPlugin.extract({
use: [
{ loader: 'css-loader', options: { importLoaders: 1, minimize: (env === 'production'), sourceMap: (env === 'production') } },
'resolve-url-loader',
'sass-loader?sourceMap',
{
loader: 'postcss-loader',
options: {
config: {
ctx: {
cssnext: {
warnForDuplicates: false,
features: {
autoprefixer: false
}
},
autoprefixer: {},
lost: {}
}
}
}
}
]
})
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function(module) {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module.context.indexOf('node_modules') !== -1;
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest'
}),
//new plugins.jsonManifest
new ManifestPlugin()
// OPTIONAL PLUGINS
// Make jQuery work with Webpack. Only include if jQuery is necessary
// new webpack.ProvidePlugin({
// $: "jquery",
// jQuery: "jquery",
// "window.jQuery": "jquery"
// })
]
// Select full version of vue instead of the (default) runtime-only build
// resolve: {
// alias: {
// 'vue$': 'vue/dist/vue.esm.js'
// }
// }
}
]);
const developmentConfig = merge([
{
devtool: 'eval-source-map',
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: '/node_modules',
loader: "eslint-loader",
options: {}
},
]
},
plugins: [
new ExtractTextPlugin('[name].css'),
// CSS linting
new StylelintPlugin(),
new BrowserSyncPlugin({
notify: false,
proxy: `${PATHCONFIG.PROXY_ADDRESS}`,
}, {
files: [
'craft/templates/**/*.twig',
'public/dist/**/*.js',
'public/dist/**/*.css'
]
})
]
}
]);
const productionConfig = merge([
{
devtool: 'source-map',
output: {
filename: '[name].[chunkhash].js'
},
plugins: [
// Cleanup dist folder
new CleanWebpackPlugin([`${PATHCONFIG.BUILD_ROOT}`], {
root: __dirname,
exclude: [ 'app.js', 'app.css', 'vendor.js', 'manifest.js' ] // Do not cleanup the dev files by default
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new ExtractTextPlugin('[name].[contenthash].css')
]
}
]);
module.exports = () => {
console.log(env);
if (env === 'production') {
return merge(commonConfig, productionConfig);
}
return merge(commonConfig, developmentConfig);
};
Using Homestead and newest versions of NodeJS and NPM.
Any help would be very welcome, because I do not have any clue anymore :)
Version 2 seems to break with Laravel Mix. Webpack says its building but fails to launch the browser, and browsersync. Webpack says its watching files and then almost immediately says its done and drops back to terminal prompt.
This breaks:
"devDependencies": {
"browser-sync": "^2.23.6",
"browser-sync-webpack-plugin": "^2.0.1",
"cross-env": "^5.0.5",
"laravel-mix": "^2.1.7"
},
This works
"devDependencies": {
"browser-sync": "^2.23.6",
"browser-sync-webpack-plugin": "^1.2.0",
"cross-env": "^5.0.5",
"laravel-mix": "^2.1.7"
},
Any idea what the problem could be? Trouble is, Mix auto installs the most recent version of browser-sync-webpack-plugin
so i'm sure I won't be the only person to run into it.
I'm using it standalone, not in a Laravel project.
I am coming from using browser sync with gulp and there, when I change the CSS/Sass browser sync inject the CSS without cause full reload, but here it's not the same behavior, there is a way to solve this?
Hello, how it use with webpackHotDevClient from react-dev-utils?
Example pkg https://github.com/react-doc/webpack-hot-dev-clients/blob/master/webpackHotDevClient.js
It use window.location.hostname & window.location.port for work this
I can't get rid of the 'Rebuilding...' popup in the top right corner even though I define 'notify: false'
Hello!
Thanks for this extremely helpful plugin.
I'm using webpack to also watch for changes to markup files. For example I compile .pug files to .html when a file is changed.
fs.watch( site.system.source, ( eventType, filename ) => {
if ( eventType != 'change' || filename.indexOf( towatch ) == -1 ) return
return publishpug( site )
} )
What I would like to do is reload browsersync on these changes. Ideally:
// Browser sync stuff
const BrowserSyncPlugin = require( 'browser-sync-webpack-plugin' )
const bsync = new BrowserSyncPlugin({})
fs.watch( site.system.source, ( eventType, filename ) => {
if ( eventType != 'change' || filename.indexOf( towatch ) == -1 ) return
return publishpug( site ).then( f => { bsync.reload( ) } ) // This would reload browser sync
} )
Currently trying this gives a:
TypeError: bsync.reload is not a function
I can't find any option for this in the documentation but would love to be able to do this.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.