fixes #33: webpack 2 - the future is here

This commit is contained in:
Davide Alberani 2017-03-13 20:52:53 +01:00
parent af38c21064
commit eda55092d3
10 changed files with 192 additions and 154 deletions

View file

@ -1,36 +1,35 @@
// https://github.com/shelljs/shelljs
require('./check-versions')() require('./check-versions')()
require('shelljs/global')
env.NODE_ENV = 'production'
var path = require('path') process.env.NODE_ENV = 'production'
var config = require('../config')
var ora = require('ora') var ora = require('ora')
var rm = require('rimraf')
var path = require('path')
var chalk = require('chalk')
var webpack = require('webpack') var webpack = require('webpack')
var config = require('../config')
var webpackConfig = require('./webpack.prod.conf') var webpackConfig = require('./webpack.prod.conf')
console.log(
' Tip:\n' +
' Built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
)
var spinner = ora('building for production...') var spinner = ora('building for production...')
spinner.start() spinner.start()
var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory) rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
rm('-rf', assetsPath)
mkdir('-p', assetsPath)
cp('-R', 'static/*', assetsPath)
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err if (err) throw err
process.stdout.write(stats.toString({ webpack(webpackConfig, function (err, stats) {
colors: true, spinner.stop()
modules: false, if (err) throw err
children: false, process.stdout.write(stats.toString({
chunks: false, colors: true,
chunkModules: false modules: false,
}) + '\n') children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
}) })

View file

@ -1,9 +1,9 @@
var semver = require('semver')
var chalk = require('chalk') var chalk = require('chalk')
var semver = require('semver')
var packageConfig = require('../package.json') var packageConfig = require('../package.json')
var exec = function (cmd) {
return require('child_process') function exec (cmd) {
.execSync(cmd).toString().trim() return require('child_process').execSync(cmd).toString().trim()
} }
var versionRequirements = [ var versionRequirements = [

View file

@ -1,15 +1,21 @@
require('./check-versions')() require('./check-versions')()
var config = require('../config') var config = require('../config')
if (!process.env.NODE_ENV) process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
var opn = require('opn')
var path = require('path') var path = require('path')
var express = require('express') var express = require('express')
var webpack = require('webpack') var webpack = require('webpack')
var opn = require('opn')
var proxyMiddleware = require('http-proxy-middleware') var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = require('./webpack.dev.conf') var webpackConfig = require('./webpack.dev.conf')
// default port where dev server listens for incoming traffic // default port where dev server listens for incoming traffic
var port = process.env.PORT || config.dev.port var port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
var autoOpenBrowser = !!config.dev.autoOpenBrowser
// Define HTTP proxies to your custom API backend // Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware // https://github.com/chimurai/http-proxy-middleware
var proxyTable = config.dev.proxyTable var proxyTable = config.dev.proxyTable
@ -19,13 +25,12 @@ var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, { var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath, publicPath: webpackConfig.output.publicPath,
stats: { quiet: true
colors: true,
chunks: false
}
}) })
var hotMiddleware = require('webpack-hot-middleware')(compiler) var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {}
})
// force page reload when html-webpack-plugin template changes // force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) { compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
@ -40,7 +45,7 @@ Object.keys(proxyTable).forEach(function (context) {
if (typeof options === 'string') { if (typeof options === 'string') {
options = { target: options } options = { target: options }
} }
app.use(proxyMiddleware(context, options)) app.use(proxyMiddleware(options.filter || context, options))
}) })
// handle fallback for HTML5 history API // handle fallback for HTML5 history API
@ -57,16 +62,20 @@ app.use(hotMiddleware)
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
app.use(staticPath, express.static('./static')) app.use(staticPath, express.static('./static'))
var uri = 'http://localhost:' + port
devMiddleware.waitUntilValid(function () {
console.log('> Listening at ' + uri + '\n')
})
module.exports = app.listen(port, function (err) { module.exports = app.listen(port, function (err) {
if (err) { if (err) {
console.log(err) console.log(err)
return return
} }
var uri = 'http://localhost:' + port
console.log('Listening at ' + uri + '\n')
// when env is testing, don't need open it // when env is testing, don't need open it
if (process.env.NODE_ENV !== 'testing') { if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
opn(uri) opn(uri)
} }
}) })

View file

@ -11,38 +11,48 @@ exports.assetsPath = function (_path) {
exports.cssLoaders = function (options) { exports.cssLoaders = function (options) {
options = options || {} options = options || {}
var cssLoader = {
loader: 'css-loader',
options: {
minimize: process.env.NODE_ENV === 'production',
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin // generate loader string to be used with extract text plugin
function generateLoaders (loaders) { function generateLoaders (loader, loaderOptions) {
var sourceLoader = loaders.map(function (loader) { var loaders = [cssLoader]
var extraParamChar if (loader) {
if (/\?/.test(loader)) { loaders.push({
loader = loader.replace(/\?/, '-loader?') loader: loader + '-loader',
extraParamChar = '&' options: Object.assign({}, loaderOptions, {
} else { sourceMap: options.sourceMap
loader = loader + '-loader' })
extraParamChar = '?' })
} }
return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : '')
}).join('!')
// Extract CSS when that option is specified // Extract CSS when that option is specified
// (which is the case during production build) // (which is the case during production build)
if (options.extract) { if (options.extract) {
return ExtractTextPlugin.extract('vue-style-loader', sourceLoader) return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else { } else {
return ['vue-style-loader', sourceLoader].join('!') return ['vue-style-loader'].concat(loaders)
} }
} }
// http://vuejs.github.io/vue-loader/en/configurations/extract-css.html // http://vuejs.github.io/vue-loader/en/configurations/extract-css.html
return { return {
css: generateLoaders(['css']), css: generateLoaders(),
postcss: generateLoaders(['css']), postcss: generateLoaders(),
less: generateLoaders(['css', 'less']), less: generateLoaders('less'),
sass: generateLoaders(['css', 'sass?indentedSyntax']), sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders(['css', 'sass']), scss: generateLoaders('sass'),
stylus: generateLoaders(['css', 'stylus']), stylus: generateLoaders('stylus'),
styl: generateLoaders(['css', 'stylus']) styl: generateLoaders('stylus')
} }
} }
@ -54,7 +64,7 @@ exports.styleLoaders = function (options) {
var loader = loaders[extension] var loader = loaders[extension]
output.push({ output.push({
test: new RegExp('\\.' + extension + '$'), test: new RegExp('\\.' + extension + '$'),
loader: loader use: loader
}) })
} }
return output return output

12
build/vue-loader.conf.js Normal file
View file

@ -0,0 +1,12 @@
var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction
})
}

View file

@ -1,14 +1,11 @@
var path = require('path') var path = require('path')
var config = require('../config')
var utils = require('./utils') var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../') var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
var env = process.env.NODE_ENV function resolve (dir) {
// check env & config/index.js to decide whether to enable CSS source maps for the return path.join(__dirname, '..', dir)
// various preprocessor loaders added to vue-loader at the end of this file }
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd
module.exports = { module.exports = {
entry: { entry: {
@ -16,41 +13,33 @@ module.exports = {
}, },
output: { output: {
path: config.build.assetsRoot, path: config.build.assetsRoot,
publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath, filename: '[name].js',
filename: '[name].js' publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
}, },
resolve: { resolve: {
extensions: ['', '.js', '.vue'], extensions: ['.js', '.vue', '.json'],
fallback: [path.join(__dirname, '../node_modules')],
alias: { alias: {
'vue$': 'vue/dist/vue.common.js', 'vue$': 'vue/dist/vue.esm.js',
'src': path.resolve(__dirname, '../src'), '@': resolve('src'),
'assets': path.resolve(__dirname, '../src/assets'),
'components': path.resolve(__dirname, '../src/components')
} }
}, },
resolveLoader: {
fallback: [path.join(__dirname, '../node_modules')]
},
module: { module: {
loaders: [ rules: [
{ {
test: /\.vue$/, test: /\.vue$/,
loader: 'vue' loader: 'vue-loader',
options: vueLoaderConfig
}, },
{ {
test: /\.js$/, test: /\.js$/,
loader: 'babel', loader: 'babel-loader',
include: projectRoot, include: [resolve('src'), resolve('test')]
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
}, },
{ {
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url', loader: 'url-loader',
query: { query: {
limit: 10000, limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]') name: utils.assetsPath('img/[name].[hash:7].[ext]')
@ -58,20 +47,12 @@ module.exports = {
}, },
{ {
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url', loader: 'url-loader',
query: { query: {
limit: 10000, limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]') name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
} }
} }
] ]
},
vue: {
loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }),
postcss: [
require('autoprefixer')({
browsers: ['last 2 versions']
})
]
} }
} }

View file

@ -1,9 +1,10 @@
var config = require('../config')
var webpack = require('webpack')
var merge = require('webpack-merge')
var utils = require('./utils') var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf') var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin') var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks // add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) { Object.keys(baseWebpackConfig.entry).forEach(function (name) {
@ -12,10 +13,10 @@ Object.keys(baseWebpackConfig.entry).forEach(function (name) {
module.exports = merge(baseWebpackConfig, { module.exports = merge(baseWebpackConfig, {
module: { module: {
loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
}, },
// eval-source-map is faster for development // cheap-module-eval-source-map is faster for development
devtool: '#eval-source-map', devtool: '#cheap-module-eval-source-map',
plugins: [ plugins: [
new webpack.ProvidePlugin({ new webpack.ProvidePlugin({
$: 'jquery', $: 'jquery',
@ -27,14 +28,14 @@ module.exports = merge(baseWebpackConfig, {
'process.env': config.dev.env 'process.env': config.dev.env
}), }),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(), new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(), new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin // https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({ new HtmlWebpackPlugin({
filename: 'index.html', filename: 'index.html',
template: 'index.html', template: 'index.html',
inject: true inject: true
}) }),
new FriendlyErrorsPlugin()
] ]
}) })

View file

@ -1,16 +1,22 @@
var path = require('path') var path = require('path')
var config = require('../config')
var utils = require('./utils') var utils = require('./utils')
var webpack = require('webpack') var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge') var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf') var baseWebpackConfig = require('./webpack.base.conf')
var ExtractTextPlugin = require('extract-text-webpack-plugin') var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin') var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
var env = config.build.env var env = config.build.env
var webpackConfig = merge(baseWebpackConfig, { var webpackConfig = merge(baseWebpackConfig, {
module: { module: {
loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
}, },
devtool: config.build.productionSourceMap ? '#source-map' : false, devtool: config.build.productionSourceMap ? '#source-map' : false,
output: { output: {
@ -18,19 +24,7 @@ var webpackConfig = merge(baseWebpackConfig, {
filename: utils.assetsPath('js/[name].[chunkhash].js'), filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
}, },
vue: {
loaders: utils.cssLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
plugins: [ plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
}),
// http://vuejs.github.io/vue-loader/en/workflow/production.html // http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({ new webpack.DefinePlugin({
'process.env': env 'process.env': env
@ -38,11 +32,16 @@ var webpackConfig = merge(baseWebpackConfig, {
new webpack.optimize.UglifyJsPlugin({ new webpack.optimize.UglifyJsPlugin({
compress: { compress: {
warnings: false warnings: false
} },
sourceMap: true
}), }),
new webpack.optimize.OccurrenceOrderPlugin(),
// extract css into its own file // extract css into its own file
new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')), new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin(),
// generate dist index.html with correct asset hash for caching. // generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html // you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin // see https://github.com/ampedandwired/html-webpack-plugin
@ -79,7 +78,15 @@ var webpackConfig = merge(baseWebpackConfig, {
new webpack.optimize.CommonsChunkPlugin({ new webpack.optimize.CommonsChunkPlugin({
name: 'manifest', name: 'manifest',
chunks: ['vendor'] chunks: ['vendor']
}) }),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
] ]
}) })
@ -101,4 +108,9 @@ if (config.build.productionGzip) {
) )
} }
if (config.build.bundleAnalyzerReport) {
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig module.exports = webpackConfig

View file

@ -14,11 +14,17 @@ module.exports = {
// Before setting to `true`, make sure to: // Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin // npm install --save-dev compression-webpack-plugin
productionGzip: false, productionGzip: false,
productionGzipExtensions: ['js', 'css'] productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}, },
dev: { dev: {
env: require('./dev.env'), env: require('./dev.env'),
port: 8080, port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static', assetsSubDirectory: 'static',
assetsPublicPath: '/', assetsPublicPath: '/',
proxyTable: { proxyTable: {

View file

@ -1,6 +1,6 @@
{ {
"name": "ibt2", "name": "ibt2",
"version": "1.1.1", "version": "1.1.2",
"description": "I'll be there, 2: an oversimplified application to register attendees at a conference or event", "description": "I'll be there, 2: an oversimplified application to register attendees at a conference or event",
"author": "Davide Alberani <da@erlug.linux.it>", "author": "Davide Alberani <da@erlug.linux.it>",
"license": "Apache-2.0", "license": "Apache-2.0",
@ -34,40 +34,48 @@
"vuex": "^2.1.1" "vuex": "^2.1.1"
}, },
"devDependencies": { "devDependencies": {
"autoprefixer": "^6.4.0", "autoprefixer": "^6.7.2",
"babel": "^6.5.2", "babel-core": "^6.22.1",
"babel-core": "^6.0.0", "babel-loader": "^6.2.10",
"babel-loader": "^6.0.0", "babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-runtime": "^6.0.0", "babel-preset-env": "^1.2.1",
"babel-preset-es2015": "^6.0.0", "babel-preset-es2015": "^6.24.0",
"babel-preset-stage-2": "^6.0.0", "babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.0.0", "babel-register": "^6.22.0",
"chalk": "^1.1.3", "chalk": "^1.1.3",
"connect-history-api-fallback": "^1.1.0", "connect-history-api-fallback": "^1.3.0",
"css-loader": "^0.25.0", "copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.26.1",
"eventsource-polyfill": "^0.9.6", "eventsource-polyfill": "^0.9.6",
"express": "^4.13.3", "express": "^4.14.1",
"extract-text-webpack-plugin": "^1.0.1", "extract-text-webpack-plugin": "^2.0.0",
"file-loader": "^0.9.0", "file-loader": "^0.10.0",
"function-bind": "^1.0.2", "friendly-errors-webpack-plugin": "^1.1.3",
"html-webpack-plugin": "^2.8.1", "function-bind": "^1.1.0",
"http-proxy-middleware": "^0.17.2", "html-webpack-plugin": "^2.28.0",
"json-loader": "^0.5.4", "http-proxy-middleware": "^0.17.3",
"opn": "^4.0.2", "opn": "^4.0.2",
"ora": "^0.3.0", "optimize-css-assets-webpack-plugin": "^1.3.0",
"ora": "^1.1.0",
"rimraf": "^2.6.0",
"semver": "^5.3.0", "semver": "^5.3.0",
"shelljs": "^0.7.4",
"url-loader": "^0.5.7", "url-loader": "^0.5.7",
"vue-loader": "^10.0.0", "vue-loader": "^10.0.0",
"vue-style-loader": "^1.0.0", "vue-style-loader": "^1.0.0",
"vue-template-compiler": "^2.1.0", "vue-template-compiler": "^2.1.0",
"webpack": "^1.13.2", "webpack": "^2.2.1",
"webpack-dev-middleware": "^1.8.3", "webpack-bundle-analyzer": "^2.2.1",
"webpack-hot-middleware": "^2.12.2", "webpack-dev-middleware": "^1.10.0",
"webpack-merge": "^0.14.1" "webpack-hot-middleware": "^2.16.1",
"webpack-merge": "^2.6.1"
}, },
"engines": { "engines": {
"node": ">= 4.0.0", "node": ">= 4.0.0",
"npm": ">= 3.0.0" "npm": ">= 3.0.0"
} },
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
} }