Reorganize and refactor build routine

This commit is contained in:
QWp6t
2016-11-06 22:31:49 -08:00
parent c1bb2b3a27
commit 8c9ba0546b
8 changed files with 107 additions and 94 deletions

View File

@@ -21,15 +21,14 @@ const config = mergeWithConcat({
}, },
enabled: { enabled: {
sourceMaps: !isProduction, sourceMaps: !isProduction,
minify: isProduction, optimize: isProduction,
cacheBusting: isProduction, cacheBusting: isProduction,
watcher: !!argv.watch, watcher: !!argv.watch,
uglifyJs: !(argv.p || argv.optimizeMinimize),
}, },
watch: [], watch: [],
}, userConfig); }, userConfig);
config.watch.push(config.copy); config.watch.push(`${path.basename(config.paths.assets)}/${config.copy}`);
config.watch = uniq(config.watch); config.watch = uniq(config.watch);
Object.keys(config.entry).forEach(id => Object.keys(config.entry).forEach(id =>

View File

@@ -0,0 +1,34 @@
const path = require('path');
module.exports = (key, value) => {
if (typeof value === 'string') {
return value;
}
const manifest = value;
/**
* Hack to prepend scripts/ or styles/ to manifest keys
*
* This might need to be reworked at some point.
*
* Before:
* {
* "main.js": "scripts/main_abcdef.js"
* "main.css": "styles/main_abcdef.css"
* }
* After:
* {
* "scripts/main.js": "scripts/main_abcdef.js"
* "styles/main.css": "styles/main_abcdef.css"
* }
*/
Object.keys(manifest).forEach((src) => {
const sourcePath = path.basename(path.dirname(src));
const targetPath = path.basename(path.dirname(manifest[src]));
if (sourcePath === targetPath) {
return;
}
manifest[`${targetPath}/${src}`] = manifest[src];
delete manifest[src];
});
return manifest;
};

View File

@@ -1,16 +1,13 @@
'use strict'; // eslint-disable-line
const webpack = require('webpack'); const webpack = require('webpack');
const qs = require('qs'); const qs = require('qs');
const autoprefixer = require('autoprefixer'); const autoprefixer = require('autoprefixer');
const CleanPlugin = require('clean-webpack-plugin'); const CleanPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const imageminMozjpeg = require('imagemin-mozjpeg');
const CopyGlobsPlugin = require('./webpack.plugin.copyglobs'); const CopyGlobsPlugin = require('./webpack.plugin.copyglobs');
const mergeWithConcat = require('./util/mergeWithConcat'); const mergeWithConcat = require('./util/mergeWithConcat');
const addHotMiddleware = require('./util/addHotMiddleware');
const webpackConfigProduction = require('./webpack.config.production');
const webpackConfigWatch = require('./webpack.config.watch');
const config = require('./config'); const config = require('./config');
const assetsFilenames = (config.enabled.cacheBusting) ? config.cacheBusting : '[name]'; const assetsFilenames = (config.enabled.cacheBusting) ? config.cacheBusting : '[name]';
@@ -29,7 +26,7 @@ if (config.enabled.watcher) {
jsLoader.loaders.unshift('monkey-hot?sourceType=module'); jsLoader.loaders.unshift('monkey-hot?sourceType=module');
} }
const webpackConfig = { let webpackConfig = {
context: config.paths.assets, context: config.paths.assets,
entry: config.entry, entry: config.entry,
devtool: (config.enabled.sourceMaps ? '#source-map' : undefined), devtool: (config.enabled.sourceMaps ? '#source-map' : undefined),
@@ -118,7 +115,10 @@ const webpackConfig = {
jquery: 'jQuery', jquery: 'jQuery',
}, },
plugins: [ plugins: [
new CleanPlugin([config.paths.dist], config.paths.root), new CleanPlugin([config.paths.dist], {
root: config.paths.root,
verbose: false,
}),
new CopyGlobsPlugin({ new CopyGlobsPlugin({
// It would be nice to switch to copy-webpack-plugin, but unfortunately it doesn't // It would be nice to switch to copy-webpack-plugin, but unfortunately it doesn't
// provide a reliable way of tracking the before/after file names // provide a reliable way of tracking the before/after file names
@@ -126,14 +126,6 @@ const webpackConfig = {
output: `[path]${assetsFilenames}.[ext]`, output: `[path]${assetsFilenames}.[ext]`,
manifest: config.manifest, manifest: config.manifest,
}), }),
new ImageminPlugin({
optipng: { optimizationLevel: 7 },
gifsicle: { optimizationLevel: 3 },
pngquant: { quality: '65-90', speed: 4 },
svgo: { removeUnknownsAndDefaults: false, cleanupIDs: false },
plugins: [imageminMozjpeg({ quality: 75 })],
disable: (config.enabled.watcher),
}),
new ExtractTextPlugin({ new ExtractTextPlugin({
filename: `styles/${assetsFilenames}.css`, filename: `styles/${assetsFilenames}.css`,
allChunks: true, allChunks: true,
@@ -152,7 +144,7 @@ const webpackConfig = {
: false, : false,
}), }),
new webpack.LoaderOptionsPlugin({ new webpack.LoaderOptionsPlugin({
minimize: config.enabled.minify, minimize: config.enabled.optimize,
debug: config.enabled.watcher, debug: config.enabled.watcher,
stats: { colors: true }, stats: { colors: true },
}), }),
@@ -175,21 +167,33 @@ const webpackConfig = {
], ],
}; };
module.exports = webpackConfig; /* eslint-disable global-require */ /** Let's only load dependencies as needed */
if (config.env.optimize) {
webpackConfig = mergeWithConcat(webpackConfig, require('./webpack.config.optimize'));
}
if (config.env.production) { if (config.env.production) {
module.exports = mergeWithConcat(webpackConfig, webpackConfigProduction); webpackConfig.plugins.push(new webpack.NoErrorsPlugin());
} }
if (config.enabled.watcher) { if (config.enabled.cacheBusting) {
module.exports.entry = addHotMiddleware(webpackConfig.entry); const WebpackAssetsManifest = require('webpack-assets-manifest');
module.exports = mergeWithConcat(webpackConfig, webpackConfigWatch);
}
if (config.enabled.uglifyJs) { webpackConfig.plugins.push(
module.exports.plugins.push( new WebpackAssetsManifest({
new webpack.optimize.UglifyJsPlugin({ output: 'assets.json',
sourceMap: config.enabled.sourceMaps, space: 2,
writeToDisk: false,
assets: config.manifest,
replacer: require('./util/assetManifestsFormatter'),
}) })
); );
} }
if (config.enabled.watcher) {
webpackConfig.entry = require('./util/addHotMiddleware')(webpackConfig.entry);
webpackConfig = mergeWithConcat(webpackConfig, require('./webpack.config.watch'));
}
module.exports = webpackConfig;

View File

@@ -0,0 +1,26 @@
'use strict'; // eslint-disable-line
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const imageminMozjpeg = require('imagemin-mozjpeg');
const cssnano = require('cssnano');
const config = require('./config');
module.exports = {
plugins: [
new OptimizeCssAssetsPlugin({
cssProcessor: cssnano,
cssProcessorOptions: { discardComments: { removeAll: true } },
canPrint: true,
}),
new ImageminPlugin({
optipng: { optimizationLevel: 7 },
gifsicle: { optimizationLevel: 3 },
pngquant: { quality: '65-90', speed: 4 },
svgo: { removeUnknownsAndDefaults: false, cleanupIDs: false },
plugins: [imageminMozjpeg({ quality: 75 })],
disable: (config.enabled.watcher),
}),
],
};

View File

@@ -1,56 +0,0 @@
'use strict'; // eslint-disable-line
const WebpackAssetsManifest = require('webpack-assets-manifest');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const cssnano = require('cssnano');
const path = require('path');
const config = require('./config');
module.exports = {
plugins: [
new WebpackAssetsManifest({
output: 'assets.json',
space: 2,
writeToDisk: false,
assets: config.manifest,
replacer(key, value) {
if (typeof value === 'string') {
return value;
}
const manifest = value;
/**
* Hack to prepend scripts/ or styles/ to manifest keys
*
* This might need to be reworked at some point.
*
* Before:
* {
* "main.js": "scripts/main_abcdef.js"
* "main.css": "styles/main_abcdef.css"
* }
* After:
* {
* "scripts/main.js": "scripts/main_abcdef.js"
* "styles/main.css": "styles/main_abcdef.css"
* }
*/
Object.keys(manifest).forEach((src) => {
const sourcePath = path.basename(path.dirname(src));
const targetPath = path.basename(path.dirname(manifest[src]));
if (sourcePath === targetPath) {
return;
}
manifest[`${targetPath}/${src}`] = manifest[src];
delete manifest[src];
});
return manifest;
},
}),
new OptimizeCssAssetsPlugin({
cssProcessor: cssnano,
cssProcessorOptions: { discardComments: { removeAll: true } },
canPrint: true,
}),
],
};

View File

@@ -1,12 +1,12 @@
const webpack = require('webpack'); const webpack = require('webpack');
const BrowserSyncPlugin = require('./webpack.plugin.browsersync'); const BrowserSyncPlugin = require('./webpack.plugin.browsersync');
const mergeWithConcat = require('./util/mergeWithConcat');
const config = require('./config'); const config = require('./config');
module.exports = { module.exports = {
output: { pathinfo: true }, output: { pathinfo: true },
devtool: '#cheap-module-source-map', devtool: '#cheap-module-source-map',
stats: false,
plugins: [ plugins: [
new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(), new webpack.HotModuleReplacementPlugin(),
@@ -15,9 +15,7 @@ module.exports = {
target: config.devUrl, target: config.devUrl,
publicPath: config.publicPath, publicPath: config.publicPath,
proxyUrl: config.proxyUrl, proxyUrl: config.proxyUrl,
browserSyncOptions: mergeWithConcat({ watch: config.watch,
files: config.watch,
}, config.browserSyncOptions),
}), }),
], ],
}; };

View File

@@ -4,6 +4,7 @@ const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware');
const browserSync = require('browser-sync'); const browserSync = require('browser-sync');
const url = require('url'); const url = require('url');
const uniq = require('lodash/uniq');
const mergeWithConcat = require('./util/mergeWithConcat'); const mergeWithConcat = require('./util/mergeWithConcat');
@@ -13,6 +14,7 @@ module.exports = class {
this.compiler = null; this.compiler = null;
this.options = mergeWithConcat({ this.options = mergeWithConcat({
proxyUrl: 'https://localhost:3000', proxyUrl: 'https://localhost:3000',
watch: [],
callback() {}, callback() {},
}, options); }, options);
} }
@@ -27,7 +29,9 @@ module.exports = class {
compiler.plugin('compilation', () => this.watcher.notify('Rebuilding...')); compiler.plugin('compilation', () => this.watcher.notify('Rebuilding...'));
this.start(); this.start();
} }
// Optionally add logic for this.watcher.reload() /* You may optionally add custom logic here to trigger either of the following */
// this.watcher.reload()
// this.watcher.reload({ stream: true })
}); });
} }
start() { start() {
@@ -38,13 +42,16 @@ module.exports = class {
target: this.options.target, target: this.options.target,
middleware: this.middleware(), middleware: this.middleware(),
}, },
files: [],
}, this.options.browserSyncOptions); }, this.options.browserSyncOptions);
watcherConfig.files = uniq(watcherConfig.files.concat(this.options.watch));
this.watcher.init(watcherConfig, this.options.callback.bind(this)); this.watcher.init(watcherConfig, this.options.callback.bind(this));
} }
middleware() { middleware() {
this.webpackDevMiddleware = webpackDevMiddleware(this.compiler, { this.webpackDevMiddleware = webpackDevMiddleware(this.compiler, {
publicPath: this.options.publicPath, publicPath: this.options.publicPath,
stats: { colors: true }, stats: false,
noInfo: true,
}); });
this.webpackHotMiddleware = webpackHotMiddleware(this.compiler, { this.webpackHotMiddleware = webpackHotMiddleware(this.compiler, {
log: this.watcher.notify.bind(this.watcher), log: this.watcher.notify.bind(this.watcher),

View File

@@ -19,11 +19,12 @@
], ],
"scripts": { "scripts": {
"build": "webpack --progress --config assets/build/webpack.config.js", "build": "webpack --progress --config assets/build/webpack.config.js",
"build:production": "npm run build -s -- -p", "build:production": "webpack --progress -p --config assets/build/webpack.config.js",
"start": "npm run build -s -- --watch", "build:profile": "webpack --progress --profile --json --config assets/build/webpack.config.js",
"start": "webpack --hide-modules --watch --config assets/build/webpack.config.js",
"clean": "rimraf dist", "clean": "rimraf dist",
"lint": "eslint assets/scripts assets/build", "lint": "eslint assets/scripts assets/build",
"test": "npm run lint -s" "test": "npm run lint"
}, },
"engines": { "engines": {
"node": ">= 4.5" "node": ">= 4.5"