Merge pull request #1627 from ptrckvzn/webpack-sage-9

webpack implementation improvements
This commit is contained in:
Ben Word
2016-03-24 12:14:42 -03:00
6 changed files with 112 additions and 49 deletions

10
config.json Normal file
View File

@@ -0,0 +1,10 @@
{
"output": {
"path": "dist",
"publicPath": "/app/themes/sage/dist/"
},
"options": {
"extractStyles": true
},
"devUrl" : "http://example.dev"
}

View File

@@ -18,9 +18,11 @@
} }
], ],
"scripts": { "scripts": {
"build:production": "export SAGE_ENV=production && webpack", "build:production": "webpack -p",
"build": "export SAGE_ENV=development && webpack", "build": "webpack -d",
"watch": "export SAGE_ENV=development && node dev.js" "watch": "node watch.js",
"lint": "eslint -c .eslintrc assets/scripts",
"install": "composer install"
}, },
"engines": { "engines": {
"node": ">= 0.12.0", "node": ">= 0.12.0",
@@ -45,6 +47,7 @@
"eslint-loader": "^1.3.0", "eslint-loader": "^1.3.0",
"extract-text-webpack-plugin": "^0.9.1", "extract-text-webpack-plugin": "^0.9.1",
"file-loader": "^0.8.5", "file-loader": "^0.8.5",
"image-webpack-loader": "^1.6.3",
"imagemin-pngcrush": "^4.1.0", "imagemin-pngcrush": "^4.1.0",
"imports-loader": "^0.6.5", "imports-loader": "^0.6.5",
"monkey-hot-loader": "0.0.3", "monkey-hot-loader": "0.0.3",

View File

@@ -12,5 +12,5 @@ add_action('customize_register', function (\WP_Customize_Manager $wp_customize)
* Customizer JS * Customizer JS
*/ */
add_action('customize_preview_init', function () { add_action('customize_preview_init', function () {
wp_enqueue_script('sage/customizer.js', asset_path('customizer.js'), ['customize-preview'], null, true); wp_enqueue_script('sage/customizer.js', asset_path('scripts/customizer.js'), ['customize-preview'], null, true);
}); });

View File

@@ -6,8 +6,8 @@ use Roots\Sage\Template;
* Theme assets * Theme assets
*/ */
add_action('wp_enqueue_scripts', function () { add_action('wp_enqueue_scripts', function () {
wp_enqueue_style('sage/main.css', asset_path('main.css'), false, null); wp_enqueue_style('sage/main.css', asset_path('styles/main.css'), false, null);
wp_enqueue_script('sage/main.js', asset_path('main.js'), ['jquery'], null, true); wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
}, 100); }, 100);
/** /**

View File

@@ -1,16 +1,19 @@
/* eslint no-console: 0 */ /* eslint no-console: 0 */
process.env.SCRIPT = 'watch';
var webpack = require('webpack'), var webpack = require('webpack'),
webpackDevMiddleware = require('webpack-dev-middleware'), webpackDevMiddleware = require('webpack-dev-middleware'),
webpackHotMiddleware = require('webpack-hot-middleware'), webpackHotMiddleware = require('webpack-hot-middleware'),
browserSync = require('browser-sync'); browserSync = require('browser-sync');
var devBuildConfig = require('./webpack.config'), var devBuildConfig = require('./webpack.config'),
config = require('./config'),
compiler = webpack(devBuildConfig); compiler = webpack(devBuildConfig);
browserSync.init({ browserSync.init({
proxy: { proxy: {
target: 'http://example.dev', // change to dev server target: config.devUrl,
middleware: [ middleware: [
webpackDevMiddleware(compiler, { webpackDevMiddleware(compiler, {
publicPath: devBuildConfig.output.publicPath, publicPath: devBuildConfig.output.publicPath,

View File

@@ -7,28 +7,30 @@ var webpack = require('webpack'),
OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'), OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'),
cssnano = require('cssnano'); cssnano = require('cssnano');
var SAGE_ENV = process.env.SAGE_ENV || 'development', var config = require('./config'),
webpackConfig; webpackConfig;
var sage = { const DEBUG = (process.argv.lastIndexOf('-d') !== -1),
publicPath: '/app/themes/sage/dist/', WATCH = (process.env.SCRIPT === 'watch');
dist: path.join(__dirname, 'dist'),
manifest: 'assets.json',
// set to true to extract css in dev mode (prevents "hot" update)
extractStyles: false
};
// format output for Sage : { "name.ext": "hash.ext" } /**
* Process AssetsPlugin output
* and format for Sage: {"[name].[ext]":"[hash].[ext]"}
* @param {Object} assets passed by processOutput
* @return {String} JSON
*/
var assetsPluginProcessOutput = function (assets) { var assetsPluginProcessOutput = function (assets) {
var results = {}, var name,
name, ext,
ext; filename,
results = {};
for (name in assets) { for (name in assets) {
if (assets.hasOwnProperty(name)) { if (assets.hasOwnProperty(name)) {
for (ext in assets[name]) { for (ext in assets[name]) {
if (assets[name].hasOwnProperty(ext)) { if (assets[name].hasOwnProperty(ext)) {
results[name + '.' + ext] = assets[name][ext]; filename = name + '.' + ext;
results[filename] = path.basename(assets[name][ext]);
} }
} }
} }
@@ -36,6 +38,30 @@ var assetsPluginProcessOutput = function (assets) {
return JSON.stringify(results); return JSON.stringify(results);
} }
/**
* Loop through webpack entry
* and add the hot middleware
* @param {Object} entry webpack entry
* @return {Object} entry with hot middleware
*/
var addHotMiddleware = function (entry) {
var name,
results = {},
hotMiddlewareScript = 'webpack-hot-middleware/client?reload=true';
for (name in entry) {
if (entry.hasOwnProperty(name)) {
if (entry[name] instanceof Array !== true) {
results[name] = [entry[name]];
} else {
results[name] = entry[name].slice(0);
};
results[name].push(hotMiddlewareScript);
}
}
return results;
}
webpackConfig = { webpackConfig = {
entry: { entry: {
main: [ main: [
@@ -46,8 +72,8 @@ webpackConfig = {
] ]
}, },
output: { output: {
path: sage.dist, path: path.join(__dirname, config.output.path),
publicPath: sage.publicPath publicPath: config.output.publicPath,
}, },
module: { module: {
preLoaders: [ preLoaders: [
@@ -61,30 +87,47 @@ webpackConfig = {
{ {
test: /\.js$/, test: /\.js$/,
exclude: /node_modules/, exclude: /node_modules/,
loaders: ['monkey-hot', 'babel'] loaders: [
'monkey-hot',
'babel'
],
}, },
{ {
test: /\.css$/, test: /\.css$/,
exclude: /node_modules/, exclude: /node_modules/,
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss') loader: (WATCH) ?
'style!css?sourceMap!postcss' :
ExtractTextPlugin.extract('style', 'css?sourceMap!postcss'),
}, },
{ {
test: /\.scss$/, test: /\.scss$/,
exclude: /node_modules/, exclude: /node_modules/,
loader: ExtractTextPlugin.extract('style', 'css?sourceMap!postcss!sass?sourceMap') loader: (WATCH) ?
'style!css?sourceMap!postcss!sass?sourceMap' :
ExtractTextPlugin.extract('style', 'css?sourceMap!postcss!sass?sourceMap'),
},
{
test: /\.(png|jpg|jpeg|gif)(\?v=[0-9]+\.?[0-9]+?\.?[0-9]+?)?$/,
loaders: [
'file?name=[path][name].[ext]&context=assets/',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
],
}, },
{ {
test: /\.(ttf|eot|svg)$/, test: /\.(ttf|eot|svg)(\?v=[0-9]+\.?[0-9]+?\.?[0-9]+?)?$/,
loader: 'url?limit=10000' loader: 'file?name=[path][name].[ext]&context=assets/',
}, },
{ {
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, test: /\.woff(2)?(\?v=[0-9]+\.?[0-9]+?\.?[0-9]+?)?$/,
loader: 'url?limit=10000&mimetype=application/font-woff' loader: 'url',
query: {
limit: 10000,
mimetype: "application/font-woff",
name: "[path][name].[ext]",
context: "assets/",
}
}, },
{
test: /\.(png|jpg|jpeg|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader'
}
], ],
}, },
resolve: { extensions: [ '', '.js', '.json' ] }, resolve: { extensions: [ '', '.js', '.json' ] },
@@ -92,7 +135,7 @@ webpackConfig = {
jquery: 'jQuery' jquery: 'jQuery'
}, },
plugins: [ plugins: [
new Clean([sage.dist]), new Clean([config.output.path]),
new webpack.ProvidePlugin({ new webpack.ProvidePlugin({
$: 'jquery', $: 'jquery',
jQuery: 'jquery', jQuery: 'jquery',
@@ -100,8 +143,8 @@ webpackConfig = {
'window.Tether': 'tether' 'window.Tether': 'tether'
}), }),
new AssetsPlugin({ new AssetsPlugin({
path: sage.dist, path: config.output.path,
filename: sage.manifest, filename: 'assets.json',
fullPath: false, fullPath: false,
processOutput: assetsPluginProcessOutput, processOutput: assetsPluginProcessOutput,
}) })
@@ -113,24 +156,20 @@ webpackConfig = {
} }
}; };
if ( SAGE_ENV === 'development' ) { if (DEBUG || WATCH) {
// development // development
webpackConfig.entry.main.push('webpack-hot-middleware/client?reload=true'); webpackConfig.output.filename = 'scripts/[name].js';
webpackConfig.entry.customizer.push('webpack-hot-middleware/client?reload=true');
webpackConfig.output.filename = '[name].js';
webpackConfig.output.sourceMapFilename = '[file].map';
webpackConfig.output.pathinfo = true;
webpackConfig.debug = true;
webpackConfig.devtool = '#cheap-module-source-map';
webpackConfig.plugins.push(new webpack.optimize.OccurenceOrderPlugin()); webpackConfig.plugins.push(new webpack.optimize.OccurenceOrderPlugin());
webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin()); webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
webpackConfig.plugins.push(new webpack.NoErrorsPlugin()); webpackConfig.plugins.push(new webpack.NoErrorsPlugin());
webpackConfig.plugins.push(new ExtractTextPlugin('[name].css', { disable: !sage.extractStyles })); webpackConfig.plugins.push(new ExtractTextPlugin('styles/[name].css', {
// disable if webpack is called from the node.js api or set to false in config file
disable: (WATCH || config.options.extractStyles === false)
}));
} else { } else {
// production // default or production
webpackConfig.output.filename = '[name].[hash].js'; webpackConfig.output.filename = 'scripts/[name]-[hash].js';
webpackConfig.output.sourceMapFilename = '[file].[hash].map'; webpackConfig.plugins.push(new ExtractTextPlugin('styles/[name]-[hash].css'));
webpackConfig.plugins.push(new ExtractTextPlugin('[name].[hash].css'));
webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin()); webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin());
webpackConfig.plugins.push(new OptimizeCssAssetsPlugin({ webpackConfig.plugins.push(new OptimizeCssAssetsPlugin({
cssProcessor: cssnano, cssProcessor: cssnano,
@@ -139,4 +178,12 @@ if ( SAGE_ENV === 'development' ) {
})); }));
} }
if (WATCH) {
// development settings when called from the node.js api by the watch script
webpackConfig.entry = addHotMiddleware(webpackConfig.entry);
webpackConfig.output.pathinfo = true;
webpackConfig.debug = true;
webpackConfig.devtool = '#cheap-module-source-map';
}
module.exports = webpackConfig; module.exports = webpackConfig;