Skip to content

Commit

Permalink
Drop --info, quieten middleware and add WebpackDXPlugin
Browse files Browse the repository at this point in the history
  • Loading branch information
insin committed Jul 28, 2016
1 parent 681d706 commit 5afb308
Show file tree
Hide file tree
Showing 10 changed files with 163 additions and 24 deletions.
35 changes: 34 additions & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,37 @@ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Uses some code from create-react-app:

BSD License

For create-react-app software

Copyright (c) 2016-present, Facebook, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name Facebook nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2 changes: 0 additions & 2 deletions docs/Commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ react run <entry> [options]
- `--auto-install` - auto install missing npm dependencies
- `--fallback` - serve the index page from any path
- `--host` - hostname to bind the dev server to *[default: localhost]*
- `--info` - show webpack module info
- `--mount-id` - `id` for the `<div>` the app will render into *[default: app]*
- `--port` - port to run the dev server on *[default: 3000]*
- `--reload` - auto reload the page if hot reloading fails
Expand Down Expand Up @@ -173,7 +172,6 @@ Passing an argument for `entry` allows you to customise the entry point for your
- `--auto-install` - automatically install missing npm dependencies and save them to your app's `package.json`
- `--fallback` - fall back to serving the index page from any path, for developing apps which use the History API
- `--host` - change the hostname the dev server binds to *[default: localhost]*
- `--info` - print info about Webpack modules after rebuilds
- `--port` - change the port the dev server runs on *[default: 3000]*
- `--reload` - auto-reload the page when webpack gets stuck

Expand Down
1 change: 0 additions & 1 deletion docs/Middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ Your app's version of the Express module must be passed as the first argument.
- `autoInstall` - automatically install missing npm dependencies *[default: `false`]*
- `config` - path to a config file *[default: nwb.config.js]*
- `entry` - entry point for the app *[default: src/index.js]*
- `info` - print info about Webpack modules after rebuilds *[default: `false`]*

#### Example

Expand Down
11 changes: 5 additions & 6 deletions express.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ module.exports = function(express, options) {
_: ['serve-react-app', options.entry],
'auto-install': !!options.autoInstall,
config: options.config,
info: !!options.info
}

var webpackConfig = createServerWebpackConfig(
Expand All @@ -41,14 +40,14 @@ module.exports = function(express, options) {
var router = express.Router()

router.use(require('webpack-dev-middleware')(compiler, {
noInfo: !args.info,
noInfo: true,
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true
}
quiet: true,
}))

router.use(require('webpack-hot-middleware')(compiler))
router.use(require('webpack-hot-middleware')(compiler, {
log: false,
}))

return router
}
109 changes: 109 additions & 0 deletions src/WebpackDXPlugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import {green, red, yellow} from 'chalk'

const friendlySyntaxErrorLabel = 'Syntax error:'

export function clearConsole() {
process.stdout.write('\x1B[2J\x1B[0f')
}

function formatMessage(message) {
return message
// Make some common errors shorter:
.replace(
// Babel syntax error
'Module build failed: SyntaxError:',
friendlySyntaxErrorLabel
)
.replace(
// Webpack file not found error
/Module not found: Error: Cannot resolve 'file' or 'directory'/,
'Module not found:'
)
// Internal stacks are generally useless so we strip them
.replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, '') // at ... ...:x:y
// Webpack loader names obscure CSS filenames
.replace(/\.\/~\/css-loader!(\.\/~\/\w+-loader!)*/, '')
}

function isLikelyASyntaxError(message) {
return message.indexOf(friendlySyntaxErrorLabel) !== -1
}

export default class WebpackDXPlugin {
constructor({clear = true, successMessage = null} = {}) {
// Should the plugin clear the console after every rebuild?
this.clear = clear
// Custom message to display after successful compilation, e.g. the URL the
// dev server is running on.
this.successMessage = successMessage

this.done = this.done.bind(this)
this.invalid = this.invalid.bind(this)
}

apply(compiler) {
compiler.plugin('done', this.done)
compiler.plugin('invalid', this.invalid)
}

clearConsole() {
if (this.clear) clearConsole()
}

done(stats) {
this.clearConsole()
let hasErrors = stats.hasErrors()
let hasWarnings = stats.hasWarnings()
if (!hasErrors && !hasWarnings) {
console.log(green('Compiled successfully!'))
console.log()
if (this.successMessage) {
console.log(this.successMessage)
console.log()
}
return
}

let json = stats.toJson()
let formattedErrors = json.errors.map(message =>
`Error in ${formatMessage(message)}`
)
let formattedWarnings = json.warnings.map(message =>
`Warning in ${formatMessage(message)}`
)

if (hasErrors) {
console.log(red('Failed to compile.'))
console.log()
if (formattedErrors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them.
// This prevents a confusing ESLint parsing error preceding a much more
// useful Babel syntax error.
formattedErrors = formattedErrors.filter(isLikelyASyntaxError)
}
formattedErrors.forEach(message => {
console.log(message)
console.log()
})
return
}

if (hasWarnings) {
console.log(yellow('Compiled with warnings.'))
console.log()
formattedWarnings.forEach(message => {
console.log(message)
console.log()
})

console.log('You may use special comments to disable some warnings.')
console.log(`Use ${yellow('// eslint-disable-next-line')} to ignore the next line.`)
console.log(`Use ${yellow('/* eslint-disable */')} to ignore all warnings in a file.`)
}
}

invalid() {
this.clearConsole()
console.log('Compiling...')
}
}
1 change: 0 additions & 1 deletion src/bin/react.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ Commands:
${opt('--auto-install')} auto install missing npm dependencies
${opt('--fallback')} serve the index page from any path
${opt('--host')} hostname to bind the dev server to ${opt('[default: localhost]')}
${opt('--info')} show webpack module info
${opt('--mount-id')} id for the <div> the app will render into ${opt('[default: app]')}
${opt('--port')} port to run the dev server on ${opt('[default: 3000]')}
${opt('--reload')} auto reload the page if hot reloading fails
Expand Down
1 change: 0 additions & 1 deletion src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ Generic development commands:
${opt('--auto-install')} auto install missing npm dependencies
${opt('--fallback')} serve the index page from any path
${opt('--host')} hostname to bind the dev server to ${opt('[default: localhost]')}
${opt('--info')} show webpack module info
${opt('--port')} port to run the dev server on ${opt('[default: 3000]')}
${opt('--reload')} auto reload the page if hot reloading fails
Expand Down
4 changes: 3 additions & 1 deletion src/createWebpackConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import HashedModuleIdsPlugin from '../vendor/HashedModuleIdsPlugin'
import createBabelConfig from './createBabelConfig'
import debug from './debug'
import {deepToString, endsWith} from './utils'
import WebpackDXPlugin from './WebpackDXPlugin'

// Top-level property names reserved for webpack config
// From http://webpack.github.io/docs/configuration.html
Expand Down Expand Up @@ -293,11 +294,12 @@ export function createPlugins(server, buildConfig = {}, userConfig = {}) {
}

if (server) {
// HMR is enable by default when serving
// HMR is enabled by default when serving
if (server.hot !== false) {
plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new WebpackDXPlugin(),
)
}
plugins.push(new webpack.NamedModulesPlugin())
Expand Down
22 changes: 12 additions & 10 deletions src/devServer.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {green} from 'chalk'
import {cyan} from 'chalk'
import history from 'connect-history-api-fallback'
import express from 'express'
import webpack from 'webpack'
import {clearConsole} from './WebpackDXPlugin'

/**
* Start an express server which uses webpack-dev-middleware to build and serve
Expand All @@ -10,7 +11,7 @@ import webpack from 'webpack'
*
* If static path config is provided, express will serve static content from it.
*/
export default function server(webpackConfig, {fallback, host, noInfo, port, staticPath}, cb) {
export default function server(webpackConfig, {fallback, host, port, staticPath}, cb) {
let app = express()
let compiler = webpack(webpackConfig)

Expand All @@ -19,22 +20,23 @@ export default function server(webpackConfig, {fallback, host, noInfo, port, sta
}

app.use(require('webpack-dev-middleware')(compiler, {
noInfo,
noInfo: true,
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true,
},
quiet: true,
}))

app.use(require('webpack-hot-middleware')(compiler))
app.use(require('webpack-hot-middleware')(compiler, {
log: false,
}))

if (staticPath) {
app.use(express.static(staticPath))
}

app.listen(port, host, err => {
app.listen(port, host, (err) => {
if (err) return cb(err)
console.log(green(`nwb: dev server listening at http://${host}:${port}`))
console.log('webpack building...')
clearConsole()
console.log(cyan('Starting the development server...'))
console.log()
})
}
1 change: 0 additions & 1 deletion src/webpackServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export default function webpackServer(args, buildConfig, cb) {
devServer(webpackConfig, {
fallback: !!args.fallback,
host: args.host || 'localhost',
noInfo: !args.info,
port: args.port || 3000,
staticPath: server.staticPath,
}, cb)
Expand Down

0 comments on commit 5afb308

Please sign in to comment.