react-webpack-generators / generator-react-webpack

Yeoman generator for ReactJS and Webpack
http://newtriks.com/2013/12/31/automating-react-with-yeoman-and-grunt/
MIT License
2.88k stars 355 forks source link

Try to use Browser-sync in our kit. But failed. #266

Closed wayearn closed 8 years ago

wayearn commented 8 years ago

You guys do a good job, I love your kit to do my development, helps a lot. Here is my problem:

I try to use Browser-sync in our kit, refresh the browser automatically after change any html,css,js code!

Follow the config file here : https://github.com/Browsersync/recipes/tree/master/recipes/webpack.react-hot-loader

Changed our project's config like this:

    'use strict';
require('core-js/fn/object/assign');
const webpack = require('webpack');
const config = require('./webpack.config');
const open = require('open');
var browserSync = require('browser-sync');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var path = require('path');

var bundler = webpack(config);

browserSync({
    server: {
      baseDir: './src',

      middleware: [
        webpackDevMiddleware(bundler, {
          publicPath: path.join(__dirname,'dist','assets'),
          stats: { colors: true }
        }),
        webpackHotMiddleware(bundler)
      ]
    },
    files: [
      'src/**/*.scss',  //use for SCSS change and refresh browser
      'src/*.html'
    ]
});

The error is:

  1. F12 and console: /assets/app.jsis not loaded!
  2. Change any js code in components, the browser is refreshed, but show nothing in the page.

Anyone, any suggestions? Thank you.

sthzg commented 8 years ago

Hi @kanlidy, thanks for sharing, it's an interesting idea to combine them both. In terms of integrating browser sync with this generator, the browser-sync-webpack-plugin might be an easier, plugin-based starting point (the recipe you've linked is designed as an entry point to the config, whereas the plugin-based approach seems to fit perfectly into the existing generator setup)

The config in the advanced section looks like it should be applicable to the this generator's webpack config in the cfg directory (probably cfg/dev.js for something targeted at the dev env).

If you find some time to test this I'd be curious to hear if and how it worked out for you. Otherwise I might find some time in the coming days to check if I can get it working (and of course, maybe @weblogixx can chime in with some deeper knowledge about this).

wayearn commented 8 years ago

I really want to contribute my efforts to the project.

@sthzg Hi, I tried it and fig it out with my solution: https://github.com/kanlidy/generator-react-webpack/tree/browsersync

Here's my problem: I don't really know how to modify the yeoman config files, so I just push it all into dev. Could you please to checkout my branch, and see how it works.

And my question: How to debug Yeoman generator? I try to use node --debug <path to yo cli.js> <generator> <args>, but it can't get the list of args like debug in Webstorm.

weblogixx commented 8 years ago

Hi @kanlidy,

thank you for your help. It is really appreciated!

I think we will have to discuss if we want to support browsersync out of the box with the default project. However, we are currently working on support for foreign modules that can be more or less be set "on top" of our generator. The reason for this is that we want the generator and the underlying template as slim as possible.

@sthzg: Maybe this would be a candidate for this when we are ready with the definition?

Hint: You have not found the generator files because the generator itself gets them from another project, located under https://github.com/react-webpack-generators/react-webpack-template. All changes in the template project will automatically be available in the generator when we publish a new release. You may also use it for standalone use.

sthzg commented 8 years ago

@weblogixx yes, absolutely, I also think it is not suited for the core template. I thought it might go into the planned, separate examples repository, going along with a how-to guide

Guide:

Example repository:

@kanlidy As mentioned above, there are plans to provide more documentation (in the form of guides and examples) to common and valuable how-to questions. The browser-sync question is a very good fit for that, since it should only be a one-time modification to the config. This will also be a very good place for contributions, once it is ready.

sthzg commented 8 years ago

@kanlidy I was curious and tried to set it up (although I sticked to browser-sync-webpack-plugin).

If this is in any way interesting for you, here are the steps I took for installation (based on a fresh generator setup).

npm i -D browser-sync browser-sync-webpack-plugin

Then there was only cfg/dev.js to modify like in this Gist.

Browser Sync is working correctly with the base setup. Modifying index.html will issue a hard reload as expected.

I also chose the plugin-based integration because of changes in the next version of this template repo. If you take a look at the 2.x branch you'll see that server.js is gone and npm start will use the webpack-dev-server executable directly.

@weblogixx one thing I was already thinking about in another context, but which is also a topic here. Do you think it would be valuable to support a --noopen cli option that prevents npm start to open the browser?

E.g. when using it with browser sync, it will open two times, once on the generator port (default 8000) and once on the browser sync port (default 3000). Browser sync can be configured with open: false, but the generator will always open (often that also bugs me when I just restart the dev server an already have a tab open). If you are plus one I would file it in a separate issue and provide a PR.

weblogixx commented 8 years ago

@sthzg, yes, I think we should just remove the --open call on npm start. I heard this primarly from windows users where each open opens a new browser window or tab. OSX seems to be smart enough to just reload the original tab. In this case, we should log the output directly to the console after webpack is ready with doing is magic. Could you open another issue for this?

wayearn commented 8 years ago

@weblogixx Thank you for your hint. That's exactly what I wanted.

Here's my solution: https://github.com/kanlidy/react-webpack-template/tree/browsersync

And, I wrote a EXAMPLE.md which told How to Setup Browsersync with Generator React Webpack (Your template)

@sthzg

Your solution is better, like you said, the browser will open two times.

weblogixx commented 8 years ago

@kanlidy Nice, thank you! Would you mind if we come back to this when we are getting started with creating the new docs / examples pages? We will also remove the open call as stated in https://github.com/react-webpack-generators/react-webpack-template/issues/46.

wayearn commented 8 years ago

@weblogixx I'll focus on the project. Thank you, guys. Then, I'll close the issue.

ThiagoMiranda commented 8 years ago

@kanlidy

I've tried your solution but it didn't work with push state. So I've made this tiny update to the server.js file ( if anyone is interested ):

/*eslint no-console:0 */
'use strict';
require('core-js/fn/object/assign');
const browserSync = require('browser-sync').create();
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const stripAnsi            = require('strip-ansi');
const webpack = require('webpack');
const config = require('./webpack.config');
const open = require('open');
const modRewrite = require('connect-modrewrite');

const bundler = webpack(config);

/**
 * Run Browsersync and use middleware for Hot Module Replacement
 */

bundler.plugin('done', function (stats) {
    if (stats.hasErrors() || stats.hasWarnings()) {
        return browserSync.sockets.emit('fullscreen:message', {
            title: "Webpack Error:",
            body:  stripAnsi(stats.toString()),
            timeout: 100000
        });
    }
    browserSync.reload();
});

/**
 * Run Browsersync and use middleware for Hot Module Replacement
 */
browserSync.init({
    server: './src',
    open: false,
    logFileChanges: false,
    middleware: [
        webpackDevMiddleware(bundler, {
            publicPath: config.output.publicPath,
            stats: {colors: true}
        }),
        webpackHotMiddleware(bundler),
        modRewrite([
            '!\\.\\w+$ /index.html [L]'
        ])
    ],
    files: [
        'src/styles/*.css',
        'src/*.html'
    ]
},function(err,bs){
    open('http://localhost:'+config.devServer.port);
});