Skip to content

Commit

Permalink
feat: remove all logs and use network ip by default
Browse files Browse the repository at this point in the history
  • Loading branch information
swashata committed Oct 8, 2018
1 parent 3f508b8 commit 9aea139
Show file tree
Hide file tree
Showing 8 changed files with 135 additions and 25 deletions.
5 changes: 2 additions & 3 deletions examples/plugin/wpackio.server.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
module.exports = {
// Your LAN IP or host where you would want the live server
// Override this if you know your correct external IP (LAN)
// Otherwise, the system will always use localhost and will not
// work for external IP.
// Otherwise, the system will always try to get a LAN ip.
// This will also create some issues with file watching because for
// some reason, service-worker doesn't work on localhost?
// https://github.com/BrowserSync/browser-sync/issues/1295
// So it is recommended to change this to your LAN IP.
// If you intend to access it from your LAN (probably do?)
host: '192.168.1.144',
host: undefined,
// Your WordPress development server address
proxy: 'http://localhost:8080',
// PORT on your localhost where you would want live server to hook
Expand Down
3 changes: 3 additions & 0 deletions packages/scripts/@types/dev-ip.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
declare module 'dev-ip' {
export default function devIp():string[]|false;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module 'react-dev-utils/formatWebpackMessages' {
import * as webpack from 'webpack';
export default function formatWebpackMessages(message:any, isError?:boolean): {errors:string[], warnings:string[]}
}
3 changes: 3 additions & 0 deletions packages/scripts/@types/react-dev-utils/openBrowser.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
declare module 'react-dev-utils/openBrowser' {
export default function openBrowser(url:string):void;
}
1 change: 1 addition & 0 deletions packages/scripts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"clean-webpack-plugin": "^0.1.19",
"commander": "^2.18.0",
"css-loader": "^1.0.0",
"dev-ip": "^1.0.1",
"file-loader": "^2.0.0",
"mini-css-extract-plugin": "^0.4.3",
"optimize-css-assets-webpack-plugin": "^5.0.1",
Expand Down
20 changes: 17 additions & 3 deletions packages/scripts/src/config/CreateWebpackConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export class CreateWebpackConfig {

// If the configuration is for multiple compiler mode
// Then return an array of config.
if (this.projectConfig.files.length > 1) {
if (this.isMultiCompiler()) {
// Return an array of configuration
const config: webpack.Configuration[] = [];
this.projectConfig.files.forEach((file: FileConfig) => {
Expand All @@ -85,6 +85,13 @@ export class CreateWebpackConfig {
return this.getSingleWebpackConfig(this.projectConfig.files[0]);
}

/**
* Is the config going to be for multi-compiler?
*/
public isMultiCompiler(): boolean {
return this.projectConfig.files.length > 1;
}

/**
* Get devServer publicPath for all sorts of middlewares.
*/
Expand All @@ -100,14 +107,21 @@ export class CreateWebpackConfig {
return `${this.publicPath}__wpackio`;
}

/**
* Get Url to publicPath.
*/
public getPublicPathUrl(): string {
return `${this.getServerUrl()}${this.publicPath}`;
}

/**
* Get server URL where the hot server is live and waiting to become
* awesome.
*/
public getServerUrl(): string {
const { host, port } = this.serverConfig;

return `//${host || 'localhost'}:${port}${this.publicPath}`;
return `//${host || 'localhost'}:${port}`;
}

/**
Expand Down Expand Up @@ -143,7 +157,7 @@ export class CreateWebpackConfig {
optimizeSplitChunks,
outputPath,
publicPath: this.getPublicPath(),
serverUrl: this.getServerUrl(),
publicPathUrl: this.getPublicPathUrl(),
},
this.cwd,
this.isDev
Expand Down
9 changes: 6 additions & 3 deletions packages/scripts/src/config/WebpackConfigHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export interface WebpackConfigHelperConfig {
alias?: ProjectConfig['alias'];
optimizeSplitChunks: ProjectConfig['optimizeSplitChunks'];
publicPath: string;
serverUrl: string;
publicPathUrl: string;
}

interface CommonWebpackConfig {
Expand Down Expand Up @@ -186,7 +186,7 @@ export class WebpackConfigHelper {
// That URL of the proxied server starts from root?
// Maybe we can have a `prefix` in Config, but let's not do that
// right now.
output.publicPath = this.config.serverUrl;
output.publicPath = this.config.publicPathUrl;
}

return output;
Expand All @@ -204,7 +204,10 @@ export class WebpackConfigHelper {
'process.env.BABEL_ENV': JSON.stringify(this.env),
}),
// Clean dist directory
new cleanWebpackPlugin([this.outputPath], { root: this.cwd }),
new cleanWebpackPlugin(
[`${this.outputPath}/${this.outputInnerDir}`],
{ root: this.cwd, verbose: false }
),
// Initiate mini css extract
new miniCssExtractPlugin({
filename: `${this.outputInnerDir}/[name].css`,
Expand Down
115 changes: 99 additions & 16 deletions packages/scripts/src/scripts/Server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import browserSync from 'browser-sync';
import devIp from 'dev-ip';
import formatWebpackMessages from 'react-dev-utils/formatWebpackMessages';
import openBrowser from 'react-dev-utils/openBrowser';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
Expand All @@ -24,6 +27,9 @@ export class Server {
private bs?: browserSync.BrowserSyncInstance;
private devMiddlewares?: webpackDevMiddleware.WebpackDevMiddleware[];

private webpackConfig: CreateWebpackConfig;
private isBrowserOpened: boolean = false;

/**
* Create an instance.
*
Expand All @@ -38,6 +44,20 @@ export class Server {
this.projectConfig = projectConfig;
this.serverConfig = serverConfig;
this.cwd = cwd;
// Override serverConfig host if it is undefined
if (!this.serverConfig.host) {
const possibleHost = devIp();
if (possibleHost) {
this.serverConfig.host = possibleHost[0];
}
}
// Create the webpackConfig
this.webpackConfig = new CreateWebpackConfig(
this.projectConfig,
this.serverConfig,
this.cwd,
true
);
}

/**
Expand All @@ -52,33 +72,38 @@ export class Server {
}
// Create browserSync Instance
const bs = browserSync.create();
// Create configuration
const webpackConfig = new CreateWebpackConfig(
this.projectConfig,
this.serverConfig,
this.cwd,
true
);

// Init middleware and stuff
const middlewares: browserSync.MiddlewareHandler[] = [];
const devMiddlewares: webpackDevMiddleware.WebpackDevMiddleware[] = [];

// We can have multi-compiler or single compiler, depending on the config
// we get. And both of them works for dev and hot middleware.
const compiler = webpack(
webpackConfig.getWebpackConfig() as webpack.Configuration
);
let compiler: webpack.Compiler | webpack.MultiCompiler;
if (this.webpackConfig.isMultiCompiler()) {
compiler = webpack(
this.webpackConfig.getWebpackConfig() as webpack.Configuration[]
);
} else {
compiler = webpack(
this.webpackConfig.getWebpackConfig() as webpack.Configuration
);
}

// tslint:disable:no-object-literal-type-assertion
const devMiddleware = webpackDevMiddleware(compiler, {
stats: { colors: true },
publicPath: webpackConfig.getPublicPath(),
});
stats: false,
publicPath: this.webpackConfig.getPublicPath(),
logLevel: 'silent',
logTime: false,
} as webpackDevMiddleware.Options);

const hotMiddleware = webpackHotMiddleware(compiler, {
// Now because we are already using publicPath(dynamicPublicPath = true) in client
// we have to assume that it is prefixed. That's why we prefix it in the server too.
// Because it could be multi-compiler, I guess it will just work fine since we are
// passing in the `name` too.
path: `${webpackConfig.getHmrPath()}`,
path: `${this.webpackConfig.getHmrPath()}`,
});
// Push them
middlewares.push(devMiddleware);
Expand All @@ -89,7 +114,7 @@ export class Server {
bs.init({
// We need to silent browserSync, otherwise might conflict with
// webpack-dashboard
logLevel: 'warn',
logLevel: 'silent',
port: this.serverConfig.port,
ui: this.serverConfig.ui,
proxy: {
Expand All @@ -98,10 +123,22 @@ export class Server {
// Middleware for webpack hot reload
middleware: middlewares,
host: this.serverConfig.host,
open: 'external', // We don't want to open right away
open: false, // We don't want to open right away
notify: this.serverConfig.notify,
});

// Now open the browser, when first compilation is done
const isBrowserOpen = false;
if ((compiler as webpack.MultiCompiler).compilers) {
// Apply hooks on each one
(compiler as webpack.MultiCompiler).compilers.forEach(
this.addHooks
);
} else {
// Apply hook on the single one
this.addHooks(compiler as webpack.Compiler);
}

// Watch for user defined files, when it changes, reload
// When that change, reload
if (this.projectConfig.watch) {
Expand All @@ -119,6 +156,52 @@ export class Server {
this.devMiddlewares = devMiddlewares;
}

/**
* Add hooks to compiler instances.
*/
public addHooks = (compiler: webpack.Compiler): void => {
const { done, afterEmit } = compiler.hooks;
const serverUrl = this.webpackConfig.getServerUrl();

// Open browser on last emit of first compilation
// Q: How do I know this is the last emit, for multi-compiler
// Maybe I can count?
afterEmit.tap('wpackio-hot-server', () => {
if (!this.isBrowserOpened) {
// tslint:disable:no-http-string
console.log(`opening url http:${serverUrl}`);
openBrowser(`http:${serverUrl}`);
this.isBrowserOpened = true;
}
});

// Show stats
done.tap('wpackio-hot-server', stats => {
return;

const raw = stats.toJson('verbose');
const messages = formatWebpackMessages(raw);
if (!messages.errors.length && !messages.warnings.length) {
// console.log(
// stats.toString({
// colors: true,
// modules: false,
// chunks: false,
// })
// );
}
if (messages.errors.length) {
console.log('Failed to compile.');
messages.errors.forEach(e => console.log(e));

return;
}
if (messages.warnings.length) {
console.log('Compiled with warnings.');
messages.warnings.forEach(w => console.log(w));
}
});
};
/**
* Stop the server and clean up all processes.
*/
Expand Down

0 comments on commit 9aea139

Please sign in to comment.