Skip to content

Commit

Permalink
Refactor build routine and switch to airbnb style (roots#1703)
Browse files Browse the repository at this point in the history
- Relocate webpack stuff to assets/build
- Switch all js to airbnb code style
- Update webpack to v2.0 (beta)
- Update all other dependencies
- Assets manifest uses relative path as key [1]
- Code should be compatible with Node 4.5.0
- All dependencies have been updated

[1]: Previously the assets manifest would use the basename of a file path as
its key when looking up a cachebusted file. This was to be consistent with
Sage 8. This change makes it so that the relative path is used instead.

To clarify, review the following example.

Before:
```
{
  "main.js": "scripts/main_5f4bfc9a9f82291c6dea.js",
  "main.css": "styles/main_5f4bfc9a9f82291c6dea.css",
  "customizer.js": "scripts/customizer_5f4bfc9a9f82291c6dea.js"
}
```

After:
```
{
  "scripts/main.js":"scripts/main_5f4bfc9a9f82291c6dea.js",
  "styles/main.css":"styles/main_5f4bfc9a9f82291c6dea.css",
  "scripts/customizer.js":"scripts/customizer_5f4bfc9a9f82291c6dea.js"
}
```
  • Loading branch information
QWp6t authored Sep 5, 2016
1 parent a69d57c commit f6bdc7b
Show file tree
Hide file tree
Showing 22 changed files with 426 additions and 351 deletions.
11 changes: 4 additions & 7 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
{
"root": true,
"extends": "eslint:recommended",
"extends": "airbnb",
"globals": {
"wp": true
},
"env": {
"amd": true,
"browser": true,
"jquery": true,
"node": true,
"amd": true
"node": true
},
"parser": "babel-eslint",
"rules": {
"no-console": 0
}
"parser": "babel-eslint"
}
9 changes: 6 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ php:
- nightly

env:
- TRAVIS_NODE_VERSION="4.2" CXX="g++-4.8"
- TRAVIS_NODE_VERSION="5.3" CXX="g++-4.8"
- TRAVIS_NODE_VERSION="4" CXX="g++-4.8"
- TRAVIS_NODE_VERSION="6" CXX="g++-4.8"

matrix:
fast_finish: true
Expand All @@ -33,7 +33,7 @@ before_install:
- composer self-update

install:
- source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION
- source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION && nvm use $TRAVIS_NODE_VERSION
- travis_retry npm install -g npm@latest
- travis_retry npm install -g eslint
- node -v && npm -v
Expand All @@ -43,5 +43,8 @@ install:
- composer install -o --prefer-dist --no-interaction

script:
- npm run test
- npm run build
- npm run clean
- npm run "build:production"
- composer test
8 changes: 8 additions & 0 deletions assets/build/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"root": false,
"extends": "airbnb",
"rules": {
"import/no-extraneous-dependencies": 0,
"prefer-rest-params": 0
}
}
52 changes: 52 additions & 0 deletions assets/build/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/* eslint-disable import/no-extraneous-dependencies */

const path = require('path');
const argv = require('minimist')(process.argv.slice(2));
const glob = require('glob-all');
const merge = require('lodash/merge');

const mergeWithConcat = require('./util/mergeWithConcat');
const userConfig = require('../config');

const isProduction = !!((argv.env && argv.env.production) || argv.p);
const rootPath = (userConfig.paths && userConfig.paths.root)
? userConfig.paths.root
: process.cwd();

const config = mergeWithConcat({
copy: ['images/**/*'],
proxyUrl: 'http://localhost:3000',
cacheBusting: '[name]_[hash]',
paths: {
root: rootPath,
assets: path.join(rootPath, 'assets'),
dist: path.join(rootPath, 'dist'),
},
enabled: {
sourceMaps: !isProduction,
minify: isProduction,
cacheBusting: isProduction,
watcher: !!argv.watch,
uglifyJs: !(argv.p || argv.optimizeMinimize),
},
watch: [
'templates/**/*.php',
'src/**/*.php',
],
}, userConfig);

Object.keys(config.entry).forEach(id =>
config.entry[id].unshift(path.join(__dirname, 'public-path.js')));

module.exports = mergeWithConcat(config, {
env: merge({ production: isProduction, development: !isProduction }, argv.env),
entry: {
get files() {
return glob.sync(config.copy, {
cwd: config.paths.assets,
mark: true,
}).filter(file => !((file.slice(-1) === '/') || (!file.indexOf('*') === -1)))
.map(file => path.join(config.paths.assets, file));
},
},
});
8 changes: 8 additions & 0 deletions assets/build/public-path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/* eslint-env browser */
/* globals WEBPACK_PUBLIC_PATH */

// Dynamically set absolute public path from current protocol and host
if (WEBPACK_PUBLIC_PATH) {
// eslint-disable-next-line no-undef, camelcase
__webpack_public_path__ = `${location.protocol}//${location.host}${WEBPACK_PUBLIC_PATH}`;
}
14 changes: 14 additions & 0 deletions assets/build/util/mergeWithConcat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* eslint-disable import/no-extraneous-dependencies */

const mergeWith = require('lodash/mergeWith');

module.exports = function mergeWithConcat() {
const args = [].slice.call(arguments);
args.push((a, b) => {
if (Array.isArray(a) && Array.isArray(b)) {
return a.concat(b);
}
return undefined;
});
return mergeWith.apply(this, args);
};
200 changes: 200 additions & 0 deletions assets/build/webpack.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/* eslint-disable import/no-extraneous-dependencies */
const webpack = require('webpack');
const path = require('path');
const qs = require('qs');
const autoprefixer = require('autoprefixer');
const CleanPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const imageminMozjpeg = require('imagemin-mozjpeg');

const mergeWithConcat = require('./util/mergeWithConcat');
const webpackConfigProduction = require('./webpack.config.production');
const webpackConfigWatch = require('./webpack.config.watch');
const config = require('./config');

const publicPath = `${config.publicPath}/${path.basename(config.paths.dist)}/`;
const assetsFilenames = (config.enabled.cacheBusting) ? config.cacheBusting : '[name]';
const sourceMapQueryStr = (config.enabled.sourceMaps) ? '+sourceMap' : '-sourceMap';

const jsLoader = {
test: /\.js$/,
exclude: [/(node_modules|bower_components)(?![/|\\](bootstrap|foundation-sites))/],
loaders: [`babel?presets[]=${path.resolve('./node_modules/babel-preset-es2015')}&cacheDirectory`],
};

if (config.enabled.watcher) {
jsLoader.loaders.unshift('monkey-hot');
}

const webpackConfig = {
context: config.paths.assets,
entry: config.entry,
devtool: (config.enabled.sourceMaps ? '#source-map' : undefined),
output: {
path: config.paths.dist,
publicPath,
filename: `scripts/${assetsFilenames}.js`,
},
module: {
preLoaders: [
{
test: /\.js?$/,
include: config.paths.assets,
loader: 'eslint',
},
],
loaders: [
jsLoader,
{
test: /\.css$/,
include: config.paths.assets,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style',
loader: [
`css?${sourceMapQueryStr}`,
'postcss',
],
}),
},
{
test: /\.scss$/,
include: config.paths.assets,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style',
loader: [
`css?${sourceMapQueryStr}`,
'postcss',
`resolve-url?${sourceMapQueryStr}`,
`sass?${sourceMapQueryStr}`,
],
}),
},
{
test: /\.(png|jpe?g|gif|svg)$/,
include: config.paths.assets,
loaders: [
`file?${qs.stringify({
name: '[path][name].[ext]',
})}`,
],
},
{
test: /\.(ttf|eot)$/,
include: config.paths.assets,
loader: `file?${qs.stringify({
name: `[path]${assetsFilenames}.[ext]`,
})}`,
},
{
test: /\.woff2?$/,
include: config.paths.assets,
loader: `url?${qs.stringify({
limit: 10000,
mimetype: 'application/font-woff',
name: `[path]${assetsFilenames}.[ext]`,
})}`,
},
{
test: /\.(ttf|eot|woff2?|png|jpe?g|gif|svg)$/,
include: /node_modules|bower_components/,
loader: 'file',
query: {
name: `vendor/${config.cacheBusting}.[ext]`,
},
},
],
},
modules: [
config.paths.assets,
'node_modules',
'bower_components',
],
enforceExtensions: false,
externals: {
jquery: 'jQuery',
},
plugins: [
new CleanPlugin([config.paths.dist], config.paths.root),
new ImageminPlugin({
optipng: {
optimizationLevel: 7,
},
gifsicle: {
optimizationLevel: 3,
},
pngquant: {
quality: '65-90',
speed: 4,
},
svgo: {
removeUnknownsAndDefaults: false,
cleanupIDs: false,
},
jpegtran: null,
plugins: [imageminMozjpeg({
quality: 75,
})],
disable: (config.enabled.watcher),
}),
new ExtractTextPlugin({
filename: `styles/${assetsFilenames}.css`,
allChunks: true,
disable: (config.enabled.watcher),
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
Tether: 'tether',
'window.Tether': 'tether',
}),
new webpack.DefinePlugin({
WEBPACK_PUBLIC_PATH: (config.enabled.watcher)
? JSON.stringify(publicPath)
: false,
}),
new webpack.LoaderOptionsPlugin({
minimize: config.enabled.minify,
debug: config.enabled.watcher,
stats: { colors: true },
postcss: [
autoprefixer({
browsers: [
'last 2 versions',
'android 4',
'opera 12',
],
}),
],
eslint: {
failOnWarning: false,
failOnError: true,
},
}),
],
};

module.exports = webpackConfig;

if (config.env.production) {
module.exports = mergeWithConcat(webpackConfig, webpackConfigProduction);
}

if (config.enabled.watcher) {
module.exports = mergeWithConcat(webpackConfig, webpackConfigWatch);
}

if (config.enabled.uglifyJs) {
module.exports.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: config.enabled.minify ? {
drop_debugger: true,
dead_code: true,
warnings: false,
} : false,
sourceMap: config.enabled.sourceMaps,
output: { comments: false },
})
);
}
40 changes: 40 additions & 0 deletions assets/build/webpack.config.production.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/* eslint-disable import/no-extraneous-dependencies */
const AssetsPlugin = require('assets-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const cssnano = require('cssnano');
const path = require('path');

const config = require('./config');

/**
* Process AssetsPlugin output and format it
* for Sage: {"[name].[ext]":"[name]_[hash].[ext]"}
* @param {Object} assets passed by processOutput
* @return {String} JSON
*/
const assetsPluginProcessOutput = (assets) => {
const results = {};
Object.keys(assets).forEach(name => {
Object.keys(assets[name]).forEach(ext => {
const filename = `${path.dirname(assets[name][ext])}/${path.basename(`${name}.${ext}`)}`;
results[filename] = assets[name][ext];
});
});
return JSON.stringify(results);
};

module.exports = {
plugins: [
new AssetsPlugin({
path: config.paths.dist,
filename: 'assets.json',
fullPath: false,
processOutput: assetsPluginProcessOutput,
}),
new OptimizeCssAssetsPlugin({
cssProcessor: cssnano,
cssProcessorOptions: { discardComments: { removeAll: true } },
canPrint: true,
}),
],
};
Loading

0 comments on commit f6bdc7b

Please sign in to comment.