From fa41989328a78dc55fa60f54bd7003a4b28ed873 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 7 Apr 2017 13:55:53 +0200 Subject: [PATCH 001/101] feat: initial commit on last structure and transforms --- lib/creator/transformations/entry/entry.js | 22 +++++++++++ lib/creator/transformations/index.js | 39 +++++++++++++++++--- lib/creator/transformations/output/output.js | 3 ++ 3 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 lib/creator/transformations/entry/entry.js create mode 100644 lib/creator/transformations/output/output.js diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js new file mode 100644 index 00000000000..bd772725c40 --- /dev/null +++ b/lib/creator/transformations/entry/entry.js @@ -0,0 +1,22 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ +module.exports = function(j, ast, webpackProperties) { + + function createEntryProperty(p) { + return p.value.properties.push(utils.createProperty(j, 'entry', '{}')); + } + + return ast.find(j.ObjectExpression) + .filter(p => createEntryProperty(p)); +}; diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 308d2644156..3c8bae92d4d 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -1,7 +1,13 @@ -//const chalk = require('chalk'); -//const validateSchema = require('../../utils/validateSchema.js'); -//const webpackOptionsSchema = require('../../utils/webpackOptionsSchema.json'); -//const WebpackOptionsValidationError = require('../../utils/WebpackOptionsValidationError'); +const fs = require('fs'); +const chalk = require('chalk'); +const validateSchema = require('../../utils/validateSchema.js'); +const webpackOptionsSchema = require('../../utils/webpackOptionsSchema.json'); +const WebpackOptionsValidationError = require('../../utils/WebpackOptionsValidationError'); +const j = require('jscodeshift'); +const pEachSeries = require('p-each-series'); +const entryTransform = require('./entry/entry'); +const outputTransform = require('./output/output'); + /* * @function runTransform * @@ -11,9 +17,30 @@ * @returns { } TODO */ -module.exports = function runTransform(transformObject) { +const transformsObject = { + entryTransform, + outputTransform +}; + +module.exports = function runTransform(yeomanConfig) { + const webpackProperties = Object.keys(yeomanConfig.webpackOptions); + const transformations = Object.keys(transformsObject).map(k => transformsObject[k]); - // scaffold is done + if (webpackProperties.length !== 0) { + let ast = j('module.exports = {}'); + return pEachSeries(transformations, f => f(j, ast, webpackProperties)) + .then(() => { + const recastOptions = { + quote: 'single' + }; + const outputPath = process.cwd() + '/webpack.config.js'; + const source = ast.toSource(recastOptions); + fs.writeFileSync(outputPath, source, 'utf-8'); + }) + .catch(err => { + console.error(err); + }); + } /* const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, initialWebpackConfig); if (webpackOptionsValidationErrors.length) { diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js new file mode 100644 index 00000000000..7f7418ef72c --- /dev/null +++ b/lib/creator/transformations/output/output.js @@ -0,0 +1,3 @@ +module.exports = function(j, ast) { + return ast; +}; From 4cc5d94a643f43331585c6aafa533a3e3d86ad18 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 7 Apr 2017 19:42:45 +0200 Subject: [PATCH 002/101] feat: ast for entry --- lib/creator/transformations/entry/entry.js | 21 +++++++++++++++------ lib/creator/transformations/index.js | 5 ++--- lib/creator/yeoman/webpack-generator.js | 20 +++++++++++++++----- 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index bd772725c40..2d4e156fa94 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -11,12 +11,21 @@ createLiteral, findObjWithOneOfKeys, getRequire */ -module.exports = function(j, ast, webpackProperties) { - function createEntryProperty(p) { - return p.value.properties.push(utils.createProperty(j, 'entry', '{}')); +module.exports = function(j, ast, webpackProperties) { + function createEntryProperty(j, p) { + p.value.properties.push(utils.createProperty(j, 'entry', 'null')); + if(webpackProperties['entry'].length) { + p.value.properties[0].value.value = webpackProperties['entry']; + } else { + p.value.properties[0].value.type = 'ObjectExpression'; + p.value.properties[0].value.properties = []; + Object.keys(webpackProperties.entry).forEach( (prop) => { + p.value.properties[0].value.properties.push( + utils.createProperty(j, prop, webpackProperties.entry[prop]) + ); + }); + } } - - return ast.find(j.ObjectExpression) - .filter(p => createEntryProperty(p)); + return ast.find(j.ObjectExpression).filter(p => createEntryProperty(j, p)); }; diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 3c8bae92d4d..50e7f627da3 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -23,12 +23,11 @@ const transformsObject = { }; module.exports = function runTransform(yeomanConfig) { - const webpackProperties = Object.keys(yeomanConfig.webpackOptions); const transformations = Object.keys(transformsObject).map(k => transformsObject[k]); - if (webpackProperties.length !== 0) { + if (yeomanConfig.webpackOptions) { let ast = j('module.exports = {}'); - return pEachSeries(transformations, f => f(j, ast, webpackProperties)) + return pEachSeries(transformations, f => f(j, ast, yeomanConfig.webpackOptions)) .then(() => { const recastOptions = { quote: 'single' diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 726f4c34205..09f93ce1131 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -5,13 +5,23 @@ const Input = require('webpack-addons').Input; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { super(args, opts); - this.configuration = {}; + this.configuration = { + webpackOptions: { + entry: null + } + }; } prompting() { - return this.prompt([Input('entry', 'What is the name of the entry point in your application?'), - Input('output', 'What is the name of the output directory in your application?')]).then( (answer) => { - this.configuration.webpackOptions = answer; - }); + return this.prompt([Input('entry', 'What is the name of the entry point in your application?')]) + .then( (answer) => { + /* + this.configuration.webpackOptions.entry = { + home: answer.entry, + vendor: answer.entry + } + */ + this.configuration.webpackOptions.entry = answer.entry; + }); } config() {} childDependencies() { From ad3164eb13bffae11c750117bdc93959175adbb6 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 7 Apr 2017 21:09:01 +0200 Subject: [PATCH 003/101] feat: ast for output --- lib/creator/transformations/entry/entry.js | 2 +- .../transformations/output/output-types.js | 24 +++++++++++++++++++ lib/creator/transformations/output/output.js | 23 ++++++++++++++++-- 3 files changed, 46 insertions(+), 3 deletions(-) create mode 100644 lib/creator/transformations/output/output-types.js diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 2d4e156fa94..62cf87d913e 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -15,7 +15,7 @@ getRequire module.exports = function(j, ast, webpackProperties) { function createEntryProperty(j, p) { p.value.properties.push(utils.createProperty(j, 'entry', 'null')); - if(webpackProperties['entry'].length) { + if(webpackProperties['entry'].length || typeof webpackProperties['entry'] === 'function') { p.value.properties[0].value.value = webpackProperties['entry']; } else { p.value.properties[0].value.type = 'ObjectExpression'; diff --git a/lib/creator/transformations/output/output-types.js b/lib/creator/transformations/output/output-types.js new file mode 100644 index 00000000000..986d9229386 --- /dev/null +++ b/lib/creator/transformations/output/output-types.js @@ -0,0 +1,24 @@ +module.exports = [ + 'chunkFilename', + 'crossOriginLoading', + 'devtoolFallbackModuleFilenameTemplate', + 'devtoolLineToLine', + 'hashFunction', + 'hashDigest', + 'hashDigestLength', + 'hashSalt', + 'filename', + 'hotUpdateChunkFilename', + 'hotUpdateFunction', + 'hotUpdateMainFilename', + 'jsonpFunction', + 'libary', + 'libaryTarget', + 'path', + 'pathinfo', + 'publicPath', + 'sourceMapFilename', + 'sourcePrefix', + 'strictModuleExceptionHandling', + 'umdNamedDefine' +]; diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 7f7418ef72c..3a3643207a2 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -1,3 +1,22 @@ -module.exports = function(j, ast) { - return ast; +const webpackOutputTypes = require('./output-types'); +const utils = require('../../../transformations/utils'); + +module.exports = function(j, ast, webpackProperties) { + if(webpackProperties['output'].length) { + throw new Error('Supplying output with only no options is not supported.'); + } + + function createOutputProperties(p) { + p.value.properties.push(utils.createProperty(j, 'output', 'null')); + p.value.properties[1].value.type = 'ObjectExpression'; + p.value.properties[1].value.properties = []; + Object.keys(webpackProperties.output).forEach( (prop) => { + if(webpackOutputTypes.includes(prop)) { + p.value.properties[1].value.properties.push( + utils.createProperty(j, prop, webpackProperties.output[prop]) + ); + } + }); + } + return ast.find(j.ObjectExpression).filter(p => createOutputProperties(p)); }; From 9ce2873e1bb44c334fe3266e3186e354d1ce03d7 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 7 Apr 2017 21:23:42 +0200 Subject: [PATCH 004/101] feat: ast for context --- .../transformations/context/context.js | 24 +++++++++++++++++++ lib/creator/transformations/entry/entry.js | 2 +- lib/creator/transformations/index.js | 4 +++- lib/creator/transformations/output/output.js | 4 +++- 4 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 lib/creator/transformations/context/context.js diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js new file mode 100644 index 00000000000..687c5db3b0d --- /dev/null +++ b/lib/creator/transformations/context/context.js @@ -0,0 +1,24 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + function createContextProperty(p) { + return p.value.properties.push(utils.createProperty(j, 'context', webpackProperties['context'])); + } + if(webpackProperties['context'].length) { + return ast.find(j.ObjectExpression).filter(p => createContextProperty(p)); + } else { + throw new Error('Something went wrong, please submit an issue to the cli repo.'); + } +}; diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 62cf87d913e..da441a3d0c1 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -15,7 +15,7 @@ getRequire module.exports = function(j, ast, webpackProperties) { function createEntryProperty(j, p) { p.value.properties.push(utils.createProperty(j, 'entry', 'null')); - if(webpackProperties['entry'].length || typeof webpackProperties['entry'] === 'function') { + if((webpackProperties['entry'] && webpackProperties['entry'].length) || typeof webpackProperties['entry'] === 'function') { p.value.properties[0].value.value = webpackProperties['entry']; } else { p.value.properties[0].value.type = 'ObjectExpression'; diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 50e7f627da3..e8b07468a02 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -7,6 +7,7 @@ const j = require('jscodeshift'); const pEachSeries = require('p-each-series'); const entryTransform = require('./entry/entry'); const outputTransform = require('./output/output'); +const contextTransform = require('./context/context'); /* * @function runTransform @@ -19,7 +20,8 @@ const outputTransform = require('./output/output'); const transformsObject = { entryTransform, - outputTransform + outputTransform, + contextTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 3a3643207a2..a381657aa12 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -2,7 +2,9 @@ const webpackOutputTypes = require('./output-types'); const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { - if(webpackProperties['output'].length) { + if(!webpackProperties['output']) { + return ast; + } else if(webpackProperties['output'].length) { throw new Error('Supplying output with only no options is not supported.'); } From c0530822f2caa87ceae521e3a59c83c29090c016 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 8 Apr 2017 14:49:21 +0200 Subject: [PATCH 005/101] feat: work in progress on resolve --- .../transformations/context/context.js | 8 +-- lib/creator/transformations/entry/entry.js | 24 +++++---- lib/creator/transformations/index.js | 4 +- lib/creator/transformations/output/output.js | 18 ++++--- .../transformations/resolve/resolve-types.js | 16 ++++++ .../transformations/resolve/resolve.js | 51 +++++++++++++++++++ 6 files changed, 98 insertions(+), 23 deletions(-) create mode 100644 lib/creator/transformations/resolve/resolve-types.js create mode 100644 lib/creator/transformations/resolve/resolve.js diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 687c5db3b0d..97fb9e97a52 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -14,11 +14,13 @@ getRequire module.exports = function(j, ast, webpackProperties) { function createContextProperty(p) { - return p.value.properties.push(utils.createProperty(j, 'context', webpackProperties['context'])); + if(p.parent.value.type === 'AssignmentExpression') { + return p.value.properties.push(utils.createProperty(j, 'context', webpackProperties['context'])); + } } - if(webpackProperties['context'].length) { + if(webpackProperties['context'] && webpackProperties['context'].length) { return ast.find(j.ObjectExpression).filter(p => createContextProperty(p)); } else { - throw new Error('Something went wrong, please submit an issue to the cli repo.'); + return ast; } }; diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index da441a3d0c1..85a2fca6c67 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -15,17 +15,19 @@ getRequire module.exports = function(j, ast, webpackProperties) { function createEntryProperty(j, p) { p.value.properties.push(utils.createProperty(j, 'entry', 'null')); - if((webpackProperties['entry'] && webpackProperties['entry'].length) || typeof webpackProperties['entry'] === 'function') { - p.value.properties[0].value.value = webpackProperties['entry']; - } else { - p.value.properties[0].value.type = 'ObjectExpression'; - p.value.properties[0].value.properties = []; - Object.keys(webpackProperties.entry).forEach( (prop) => { - p.value.properties[0].value.properties.push( - utils.createProperty(j, prop, webpackProperties.entry[prop]) - ); - }); - } + p.value.properties.filter(node => node.key.value === 'entry').forEach( (prop) => { + if((webpackProperties['entry'] && webpackProperties['entry'].length) || typeof webpackProperties['entry'] === 'function') { + prop.value.value = webpackProperties['entry']; + } else { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.entry).forEach( (webpackProps) => { + prop.value.properties.push( + utils.createProperty(j, webpackProps, webpackProperties.entry[webpackProps]) + ); + }); + } + }); } return ast.find(j.ObjectExpression).filter(p => createEntryProperty(j, p)); }; diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index e8b07468a02..62b213538a8 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -8,6 +8,7 @@ const pEachSeries = require('p-each-series'); const entryTransform = require('./entry/entry'); const outputTransform = require('./output/output'); const contextTransform = require('./context/context'); +const resolveTransform = require('./resolve/resolve'); /* * @function runTransform @@ -21,7 +22,8 @@ const contextTransform = require('./context/context'); const transformsObject = { entryTransform, outputTransform, - contextTransform + contextTransform, + resolveTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index a381657aa12..9813de9d217 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -10,14 +10,16 @@ module.exports = function(j, ast, webpackProperties) { function createOutputProperties(p) { p.value.properties.push(utils.createProperty(j, 'output', 'null')); - p.value.properties[1].value.type = 'ObjectExpression'; - p.value.properties[1].value.properties = []; - Object.keys(webpackProperties.output).forEach( (prop) => { - if(webpackOutputTypes.includes(prop)) { - p.value.properties[1].value.properties.push( - utils.createProperty(j, prop, webpackProperties.output[prop]) - ); - } + p.value.properties.filter( node => node.key.value === 'output').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.output).forEach( (webpackProp) => { + if(webpackOutputTypes.includes(webpackProp)) { + prop.value.properties.push( + utils.createProperty(j, webpackProp, webpackProperties.output[webpackProp]) + ); + } + }); }); } return ast.find(j.ObjectExpression).filter(p => createOutputProperties(p)); diff --git a/lib/creator/transformations/resolve/resolve-types.js b/lib/creator/transformations/resolve/resolve-types.js new file mode 100644 index 00000000000..c989f3cdbf7 --- /dev/null +++ b/lib/creator/transformations/resolve/resolve-types.js @@ -0,0 +1,16 @@ +module.exports = [ + 'alias', + 'aliasFields', + 'descriptionFiles', + 'enforceExtension', + 'enforceModuleExtension', + 'extensions', + 'mainFields', + 'mainFiles', + 'modules', + 'unsafeCache', + {resolveLoader: 'moduleExtensions'}, + 'plugins', + 'symlinks', + 'cachePredicate' +]; diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js new file mode 100644 index 00000000000..f0a2accabd7 --- /dev/null +++ b/lib/creator/transformations/resolve/resolve.js @@ -0,0 +1,51 @@ +const utils = require('../../../transformations/utils'); +const resolveTypes = require('./resolve-types'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + function createResolveProperties(j, p) { + if(webpackProperties['resolve']) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'resolve', 'null')); + } + p.value.properties.filter(node => node.key.value === 'resolve').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.resolve).filter( (webpackProp) => { + if(resolveTypes.includes(webpackProp)) { + if(Array.isArray(webpackProperties.resolve[webpackProp])) { + // if we got a type, we make it an array + } else { + prop.value.properties.push(utils.createProperty(j, webpackProp, null)); + prop.value.properties[0].value.type = 'ObjectExpression'; + prop.value.properties[0].value.properties = []; + Object.keys(webpackProperties.resolve[webpackProp]).forEach( (resolveProps) => { + prop.value.properties[0].value.properties.push( + utils.createProperty(j, resolveProps, webpackProperties.resolve[webpackProp][resolveProps]) + ); + }); + } + } + }); + }); + } + else if(webpackProperties['resolve'].length) { + throw new Error('Resolve needs properties'); + } + else { + return ast; + } + } + return ast.find(j.ObjectExpression).filter(p => createResolveProperties(j, p)); +}; From 9635c9625f7ed252b58cc20151ee784d9621e3bb Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 8 Apr 2017 15:11:43 +0200 Subject: [PATCH 006/101] feat: add transform structure for all --- .../transformations/devServer/dev-server.js | 17 +++++++++++++++++ lib/creator/transformations/devTool/dev-tool.js | 17 +++++++++++++++++ .../transformations/externals/externals.js | 17 +++++++++++++++++ lib/creator/transformations/node/node.js | 17 +++++++++++++++++ lib/creator/transformations/other/other.js | 17 +++++++++++++++++ .../transformations/performance/performance.js | 17 +++++++++++++++++ lib/creator/transformations/plugins/plugins.js | 17 +++++++++++++++++ lib/creator/transformations/stats/stats.js | 17 +++++++++++++++++ lib/creator/transformations/target/target.js | 17 +++++++++++++++++ lib/creator/transformations/watch/watch.js | 17 +++++++++++++++++ 10 files changed, 170 insertions(+) create mode 100644 lib/creator/transformations/devServer/dev-server.js create mode 100644 lib/creator/transformations/devTool/dev-tool.js create mode 100644 lib/creator/transformations/externals/externals.js create mode 100644 lib/creator/transformations/node/node.js create mode 100644 lib/creator/transformations/other/other.js create mode 100644 lib/creator/transformations/performance/performance.js create mode 100644 lib/creator/transformations/plugins/plugins.js create mode 100644 lib/creator/transformations/stats/stats.js create mode 100644 lib/creator/transformations/target/target.js create mode 100644 lib/creator/transformations/watch/watch.js diff --git a/lib/creator/transformations/devServer/dev-server.js b/lib/creator/transformations/devServer/dev-server.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/devServer/dev-server.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; diff --git a/lib/creator/transformations/devTool/dev-tool.js b/lib/creator/transformations/devTool/dev-tool.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/devTool/dev-tool.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/externals/externals.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/node/node.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; diff --git a/lib/creator/transformations/other/other.js b/lib/creator/transformations/other/other.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/other/other.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/performance/performance.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/plugins/plugins.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/stats/stats.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/target/target.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js new file mode 100644 index 00000000000..8336fed5eda --- /dev/null +++ b/lib/creator/transformations/watch/watch.js @@ -0,0 +1,17 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + return ast.find(j.ObjectExpression); +}; From f92af9c19cdc3d22c618ed8b2f93ae64e9605bba Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 8 Apr 2017 15:31:47 +0200 Subject: [PATCH 007/101] fix: remove rx from the project --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index 43f84a140f3..f9fc98705f8 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,6 @@ "p-each-series": "^1.0.0", "p-lazy": "^1.0.0", "recast": "git://github.com/kalcifer/recast.git#bug/allowbreak", - "rx": "^4.1.0", "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", "webpack-addons": "0.0.20", From 9977025c2bbd44cfcfcc5bdf47cef24e1795f05c Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 8 Apr 2017 15:37:23 +0200 Subject: [PATCH 008/101] fix: return ast on no prop at resolve --- lib/creator/transformations/entry/entry.js | 4 ++-- lib/creator/transformations/resolve/resolve.js | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 85a2fca6c67..4e88309965b 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -13,7 +13,7 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - function createEntryProperty(j, p) { + function createEntryProperty(p) { p.value.properties.push(utils.createProperty(j, 'entry', 'null')); p.value.properties.filter(node => node.key.value === 'entry').forEach( (prop) => { if((webpackProperties['entry'] && webpackProperties['entry'].length) || typeof webpackProperties['entry'] === 'function') { @@ -29,5 +29,5 @@ module.exports = function(j, ast, webpackProperties) { } }); } - return ast.find(j.ObjectExpression).filter(p => createEntryProperty(j, p)); + return ast.find(j.ObjectExpression).filter(p => createEntryProperty(p)); }; diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index f0a2accabd7..0383692e6d2 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -14,7 +14,7 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - function createResolveProperties(j, p) { + function createResolveProperties(p) { if(webpackProperties['resolve']) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(utils.createProperty(j, 'resolve', 'null')); @@ -40,12 +40,12 @@ module.exports = function(j, ast, webpackProperties) { }); }); } - else if(webpackProperties['resolve'].length) { + else if(webpackProperties['resolve'] && webpackProperties['resolve'].length) { throw new Error('Resolve needs properties'); } else { return ast; } } - return ast.find(j.ObjectExpression).filter(p => createResolveProperties(j, p)); + return ast.find(j.ObjectExpression).filter(p => createResolveProperties(p)); }; From 2c6d1de52583e005876535d428f4f45cf755c8fa Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 8 Apr 2017 20:27:17 +0200 Subject: [PATCH 009/101] feat: ast for resolve --- lib/creator/transformations/entry/entry.js | 30 ++++++----- lib/creator/transformations/output/output.js | 24 +++++---- .../transformations/resolve/resolve-types.js | 1 - .../transformations/resolve/resolve.js | 42 +++++++++++---- lib/creator/yeoman/webpack-generator.js | 52 +++++++++++++++++-- 5 files changed, 110 insertions(+), 39 deletions(-) diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 4e88309965b..8782a15f514 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -14,20 +14,22 @@ getRequire module.exports = function(j, ast, webpackProperties) { function createEntryProperty(p) { - p.value.properties.push(utils.createProperty(j, 'entry', 'null')); - p.value.properties.filter(node => node.key.value === 'entry').forEach( (prop) => { - if((webpackProperties['entry'] && webpackProperties['entry'].length) || typeof webpackProperties['entry'] === 'function') { - prop.value.value = webpackProperties['entry']; - } else { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.entry).forEach( (webpackProps) => { - prop.value.properties.push( - utils.createProperty(j, webpackProps, webpackProperties.entry[webpackProps]) - ); - }); - } - }); + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'entry', 'null')); + p.value.properties.filter(node => node.key.value === 'entry').forEach( (prop) => { + if((webpackProperties['entry'] && webpackProperties['entry'].length) || typeof webpackProperties['entry'] === 'function') { + prop.value.value = webpackProperties['entry']; + } else { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.entry).forEach( (webpackProps) => { + prop.value.properties.push( + utils.createProperty(j, webpackProps, webpackProperties.entry[webpackProps]) + ); + }); + } + }); + } } return ast.find(j.ObjectExpression).filter(p => createEntryProperty(p)); }; diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 9813de9d217..691b9e7aa45 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -9,18 +9,20 @@ module.exports = function(j, ast, webpackProperties) { } function createOutputProperties(p) { - p.value.properties.push(utils.createProperty(j, 'output', 'null')); - p.value.properties.filter( node => node.key.value === 'output').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.output).forEach( (webpackProp) => { - if(webpackOutputTypes.includes(webpackProp)) { - prop.value.properties.push( - utils.createProperty(j, webpackProp, webpackProperties.output[webpackProp]) - ); - } + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'output', 'null')); + p.value.properties.filter( node => node.key.value === 'output').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.output).forEach( (webpackProp) => { + if(webpackOutputTypes.includes(webpackProp)) { + prop.value.properties.push( + utils.createProperty(j, webpackProp, webpackProperties.output[webpackProp]) + ); + } + }); }); - }); + } } return ast.find(j.ObjectExpression).filter(p => createOutputProperties(p)); }; diff --git a/lib/creator/transformations/resolve/resolve-types.js b/lib/creator/transformations/resolve/resolve-types.js index c989f3cdbf7..0971aa1d858 100644 --- a/lib/creator/transformations/resolve/resolve-types.js +++ b/lib/creator/transformations/resolve/resolve-types.js @@ -9,7 +9,6 @@ module.exports = [ 'mainFiles', 'modules', 'unsafeCache', - {resolveLoader: 'moduleExtensions'}, 'plugins', 'symlinks', 'cachePredicate' diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index 0383692e6d2..a35160f93c1 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -22,18 +22,42 @@ module.exports = function(j, ast, webpackProperties) { p.value.properties.filter(node => node.key.value === 'resolve').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; - Object.keys(webpackProperties.resolve).filter( (webpackProp) => { - if(resolveTypes.includes(webpackProp)) { + Object.keys(webpackProperties.resolve).forEach( (webpackProp) => { + if(resolveTypes.includes(webpackProp) || webpackProp === 'resolveLoader') { if(Array.isArray(webpackProperties.resolve[webpackProp])) { // if we got a type, we make it an array - } else { + const resolveArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); + webpackProperties.resolve[webpackProp].forEach( (n) => { + return resolveArray.value.elements.push(j.literal(n)); + }); + prop.value.properties.push(resolveArray); + } + else if(typeof(webpackProperties.resolve[webpackProp]) === 'boolean') { + let boolExp = j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.resolve[webpackProp])); + prop.value.properties.push(boolExp); + } else if(typeof(webpackProperties.resolve[webpackProp]) === 'function') { + // function declr. + } + else { prop.value.properties.push(utils.createProperty(j, webpackProp, null)); - prop.value.properties[0].value.type = 'ObjectExpression'; - prop.value.properties[0].value.properties = []; - Object.keys(webpackProperties.resolve[webpackProp]).forEach( (resolveProps) => { - prop.value.properties[0].value.properties.push( - utils.createProperty(j, resolveProps, webpackProperties.resolve[webpackProp][resolveProps]) - ); + prop.value.properties.forEach( (resolveProp) => { + if(resolveProp.key.value === webpackProp) { + resolveProp.value.type = 'ObjectExpression'; + resolveProp.value.properties = []; + Object.keys(webpackProperties.resolve[webpackProp]).forEach( (aliasProps) => { + if(Array.isArray(webpackProperties.resolve[webpackProp][aliasProps])) { + const resolveLoaderArray = j.property('init', j.identifier(aliasProps), j.arrayExpression([])); + webpackProperties.resolve[webpackProp][aliasProps].forEach( (n) => { + return resolveLoaderArray.value.elements.push(j.literal(n)); + }); + resolveProp.value.properties.push(resolveLoaderArray); + } else { + resolveProp.value.properties.push( + utils.createProperty(j, aliasProps, webpackProperties.resolve[webpackProp][aliasProps]) + ); + } + }); + } }); } } diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 09f93ce1131..15c7d2ded1a 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -7,7 +7,14 @@ module.exports = class WebpackGenerator extends Generator { super(args, opts); this.configuration = { webpackOptions: { - entry: null + output: { + filename: null, + path: null + }, + resolve: { + alias: {}, + aliasFields: [] + } } }; } @@ -16,11 +23,48 @@ module.exports = class WebpackGenerator extends Generator { .then( (answer) => { /* this.configuration.webpackOptions.entry = { - home: answer.entry, - vendor: answer.entry + vendor: 'home', + js: 'yes', + ohye: 'no' + }; + this.configuration.webpackOptions.output.filename = 'hello'; + this.configuration.webpackOptions.output.path = 'dist/assets'; + this.configuration.webpackOptions.output.pathinfo = true; + this.configuration.webpackOptions.output.publicPath = "https://newbie.com" + this.configuration.webpackOptions.output.sourceMapFilename = "[name].map" + + // buggy + this.configuration.webpackOptions.output.sourcePrefix = `${"\t"}` + + this.configuration.webpackOptions.output.umdNamedDefine = true; + this.configuration.webpackOptions.output.strictModuleExceptionHandling = true; + + this.configuration.webpackOptions.context = '/hello' + + this.configuration.webpackOptions.resolve.alias.hello = ':)' + this.configuration.webpackOptions.resolve.aliasFields = ["browser"] + this.configuration.webpackOptions.resolve.descriptionFiles = ['a', 'b'] + this.configuration.webpackOptions.resolve.enforceExtension = false + this.configuration.webpackOptions.resolve.enforceModuleExtension = false + this.configuration.webpackOptions.resolve.extensions = ['hey', 'gi'] + this.configuration.webpackOptions.resolve.mainFields = ["mod", 'ho', 'bo'] + this.configuration.webpackOptions.resolve.mainFiles = ["index"] + this.configuration.webpackOptions.resolve.modules = ["Heo"] + this.configuration.webpackOptions.resolve.unsafeCache = true + this.configuration.webpackOptions.resolve.resolveLoader = { + modules: ["node_modules"], + extensions: [".js", ".json"], + mainFields: ["loader", "main"], + moduleExtensions: ['-loader'] + } + this.configuration.webpackOptions.resolve.plugins = []; + this.configuration.webpackOptions.resolve.symlinks = true; + + // buggy + this.configuration.webpackOptions.resolve.cachePredicate = function() { + return true } */ - this.configuration.webpackOptions.entry = answer.entry; }); } config() {} From 00e1ecadc8cb7edaa7d61dae189baf2938d21a68 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 12:34:18 +0200 Subject: [PATCH 010/101] feat: ast for devtool --- lib/creator/transformations/devTool/dev-tool.js | 11 ++++++++++- lib/creator/transformations/index.js | 5 +++-- lib/creator/yeoman/webpack-generator.js | 6 +----- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/lib/creator/transformations/devTool/dev-tool.js b/lib/creator/transformations/devTool/dev-tool.js index 8336fed5eda..b48553a5cd7 100644 --- a/lib/creator/transformations/devTool/dev-tool.js +++ b/lib/creator/transformations/devTool/dev-tool.js @@ -13,5 +13,14 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); + function createDevToolProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + return p.value.properties.push(utils.createProperty(j, 'devtool', webpackProperties['devtool'])); + } + } + if(webpackProperties['devtool'] && webpackProperties['devtool'].length) { + return ast.find(j.ObjectExpression).filter(p => createDevToolProperty(p)); + } else { + return ast; + } }; diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 62b213538a8..c6369bd5187 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -9,7 +9,7 @@ const entryTransform = require('./entry/entry'); const outputTransform = require('./output/output'); const contextTransform = require('./context/context'); const resolveTransform = require('./resolve/resolve'); - +const devtoolTransform = require('./devtool/dev-tool'); /* * @function runTransform * @@ -23,7 +23,8 @@ const transformsObject = { entryTransform, outputTransform, contextTransform, - resolveTransform + resolveTransform, + devtoolTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 15c7d2ded1a..af10ac5dbb7 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -59,11 +59,7 @@ module.exports = class WebpackGenerator extends Generator { } this.configuration.webpackOptions.resolve.plugins = []; this.configuration.webpackOptions.resolve.symlinks = true; - - // buggy - this.configuration.webpackOptions.resolve.cachePredicate = function() { - return true - } + this.configuration.webpackOptions.devtool = 'eval' */ }); } From 7f8da3136e54d66952a1114e7c6922b0798e2ab5 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 12:38:31 +0200 Subject: [PATCH 011/101] feat: art for target --- lib/creator/transformations/index.js | 5 ++++- lib/creator/transformations/target/target.js | 11 ++++++++++- lib/creator/yeoman/webpack-generator.js | 1 + 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index c6369bd5187..cdb16537bad 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -10,6 +10,8 @@ const outputTransform = require('./output/output'); const contextTransform = require('./context/context'); const resolveTransform = require('./resolve/resolve'); const devtoolTransform = require('./devtool/dev-tool'); +const targetTransform = require('./target/target'); + /* * @function runTransform * @@ -24,7 +26,8 @@ const transformsObject = { outputTransform, contextTransform, resolveTransform, - devtoolTransform + devtoolTransform, + targetTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 8336fed5eda..0362af802aa 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -13,5 +13,14 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); + function createDevToolProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + return p.value.properties.push(utils.createProperty(j, 'target', webpackProperties['target'])); + } + } + if(webpackProperties['target'] && webpackProperties['target'].length) { + return ast.find(j.ObjectExpression).filter(p => createDevToolProperty(p)); + } else { + return ast; + } }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index af10ac5dbb7..cd61d069a62 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -60,6 +60,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.webpackOptions.resolve.plugins = []; this.configuration.webpackOptions.resolve.symlinks = true; this.configuration.webpackOptions.devtool = 'eval' + this.configuration.webpackOptions.target = 'async-node' */ }); } From 22df329b959999d52c17df2aeab86aa8f7f59ab1 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 12:47:52 +0200 Subject: [PATCH 012/101] feat: ast for watch --- lib/creator/transformations/index.js | 4 +++- lib/creator/transformations/target/target.js | 4 ++-- lib/creator/transformations/watch/watch.js | 11 ++++++++++- lib/creator/yeoman/webpack-generator.js | 1 + 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index cdb16537bad..c9ea0a79d3c 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -11,6 +11,7 @@ const contextTransform = require('./context/context'); const resolveTransform = require('./resolve/resolve'); const devtoolTransform = require('./devtool/dev-tool'); const targetTransform = require('./target/target'); +const watchTransform = require('./watch/watch'); /* * @function runTransform @@ -27,7 +28,8 @@ const transformsObject = { contextTransform, resolveTransform, devtoolTransform, - targetTransform + targetTransform, + watchTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 0362af802aa..6459ef1b8e3 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -13,13 +13,13 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - function createDevToolProperty(p) { + function createTargetProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { return p.value.properties.push(utils.createProperty(j, 'target', webpackProperties['target'])); } } if(webpackProperties['target'] && webpackProperties['target'].length) { - return ast.find(j.ObjectExpression).filter(p => createDevToolProperty(p)); + return ast.find(j.ObjectExpression).filter(p => createTargetProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 8336fed5eda..2b9fb0676e8 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -13,5 +13,14 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); + function createWatchProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + return p.value.properties.push(utils.createProperty(j, 'watch', webpackProperties['watch'])); + } + } + if(typeof(webpackProperties['watch']) === 'boolean' && webpackProperties.hasOwnProperty('watch')) { + return ast.find(j.ObjectExpression).filter(p => createWatchProperty(p)); + } else { + return ast; + } }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index cd61d069a62..34d286f250b 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -61,6 +61,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.webpackOptions.resolve.symlinks = true; this.configuration.webpackOptions.devtool = 'eval' this.configuration.webpackOptions.target = 'async-node' + this.configuration.webpackOptions.watch = true; */ }); } From 743f10f5b1469311932236f2f89e2c85d568a450 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 13:00:41 +0200 Subject: [PATCH 013/101] feat: sat for watchOptions --- lib/creator/transformations/index.js | 4 +- .../watch/watchOptions-types.js | 5 +++ .../transformations/watch/watchOptions.js | 41 +++++++++++++++++++ lib/creator/yeoman/webpack-generator.js | 5 +++ 4 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 lib/creator/transformations/watch/watchOptions-types.js create mode 100644 lib/creator/transformations/watch/watchOptions.js diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index c9ea0a79d3c..552458ae825 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -12,6 +12,7 @@ const resolveTransform = require('./resolve/resolve'); const devtoolTransform = require('./devtool/dev-tool'); const targetTransform = require('./target/target'); const watchTransform = require('./watch/watch'); +const watchOptionsTransform = require('./watch/watchOptions'); /* * @function runTransform @@ -29,7 +30,8 @@ const transformsObject = { resolveTransform, devtoolTransform, targetTransform, - watchTransform + watchTransform, + watchOptionsTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/watch/watchOptions-types.js b/lib/creator/transformations/watch/watchOptions-types.js new file mode 100644 index 00000000000..4a352059ebb --- /dev/null +++ b/lib/creator/transformations/watch/watchOptions-types.js @@ -0,0 +1,5 @@ +module.exports = [ + 'aggregateTimeout', + 'ignored', + 'poll' +]; diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js new file mode 100644 index 00000000000..6cd88a8717a --- /dev/null +++ b/lib/creator/transformations/watch/watchOptions.js @@ -0,0 +1,41 @@ +const utils = require('../../../transformations/utils'); +const watchOptionTypes = require('./watchOptions-types'); + +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + function createWatchOptionsProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'watchOptions', null)); + p.value.properties.filter(node => node.key.value === 'watchOptions').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { + if(watchOptionTypes.includes(watchOption)) { + prop.value.properties.push( + utils.createProperty(j, watchOption, webpackProperties['watchOptions'][watchOption]) + ); + } else { + throw new Error('Unknown Property', watchOption); + } + }); + }); + } + } + if(webpackProperties['watchOptions'] && webpackProperties['watchOptions']) { + return ast.find(j.ObjectExpression).filter(p => createWatchOptionsProperty(p)); + } else { + return ast; + } +}; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 34d286f250b..dd9195d8be7 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -62,6 +62,11 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.webpackOptions.devtool = 'eval' this.configuration.webpackOptions.target = 'async-node' this.configuration.webpackOptions.watch = true; + this.configuration.webpackOptions.watchOptions = { + aggregateTimeout: 300, + poll: 1000, + ignored: '/node_modules/' + } */ }); } From 423b8cbf28525deb51c24db198f7b0f5dbb92ede Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 13:02:03 +0200 Subject: [PATCH 014/101] fix: rename dev-tool to devtool --- .../transformations/{devTool/dev-tool.js => devtool/devtool.js} | 0 lib/creator/transformations/index.js | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename lib/creator/transformations/{devTool/dev-tool.js => devtool/devtool.js} (100%) diff --git a/lib/creator/transformations/devTool/dev-tool.js b/lib/creator/transformations/devtool/devtool.js similarity index 100% rename from lib/creator/transformations/devTool/dev-tool.js rename to lib/creator/transformations/devtool/devtool.js diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 552458ae825..6913087c022 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -9,7 +9,7 @@ const entryTransform = require('./entry/entry'); const outputTransform = require('./output/output'); const contextTransform = require('./context/context'); const resolveTransform = require('./resolve/resolve'); -const devtoolTransform = require('./devtool/dev-tool'); +const devtoolTransform = require('./devtool/devtool'); const targetTransform = require('./target/target'); const watchTransform = require('./watch/watch'); const watchOptionsTransform = require('./watch/watchOptions'); From 2f7a10c36c91468077fa52889cbfb227c77221b1 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 13:27:26 +0200 Subject: [PATCH 015/101] feat: ast for externals --- .../transformations/externals/externals.js | 53 ++++++++++++++++++- lib/creator/transformations/index.js | 4 +- lib/creator/yeoman/webpack-generator.js | 9 ++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 8336fed5eda..68ea996f073 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -13,5 +13,56 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); + function createExternalProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'externals', null)); + p.value.properties.filter(node => node.key.value === 'externals').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.externals).forEach( (webpackProp) => { + if(Array.isArray(webpackProperties.externals[webpackProp])) { + // if we got a type, we make it an array + const externalArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); + webpackProperties.externals[webpackProp].forEach( (n) => { + return externalArray.value.elements.push(j.literal(n)); + }); + prop.value.properties.push(externalArray); + } + else if(typeof(webpackProperties.externals[webpackProp]) === 'function') { + // function declr. + } + else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { + prop.value.properties.push(utils.createProperty(j, webpackProp, webpackProperties.externals[webpackProp])); + } + else { + prop.value.properties.push(utils.createProperty(j, webpackProp, null)); + prop.value.properties.forEach( (externalProp) => { + if(externalProp.key.value === webpackProp) { + externalProp.value.type = 'ObjectExpression'; + externalProp.value.properties = []; + Object.keys(webpackProperties.externals[webpackProp]).forEach( (subProps) => { + if(Array.isArray(webpackProperties.externals[webpackProp][subProps])) { + const subExternalArray = j.property('init', j.identifier(subProps), j.arrayExpression([])); + webpackProperties.externals[webpackProp][subProps].forEach( (n) => { + return subExternalArray.value.elements.push(j.literal(n)); + }); + externalProp.value.properties.push(subExternalArray); + } else { + externalProp.value.properties.push( + utils.createProperty(j, subProps, webpackProperties.externals[webpackProp][subProps]) + ); + } + }); + } + }); + } + }); + }); + } + } + if(webpackProperties['externals'] && typeof webpackProperties['externals'] === 'object') { + return ast.find(j.ObjectExpression).filter(p => createExternalProperty(p)); + } else { + return ast; + } }; diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 6913087c022..ffc85ccfdb6 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -13,6 +13,7 @@ const devtoolTransform = require('./devtool/devtool'); const targetTransform = require('./target/target'); const watchTransform = require('./watch/watch'); const watchOptionsTransform = require('./watch/watchOptions'); +const externalsTransform = require('./externals/externals'); /* * @function runTransform @@ -31,7 +32,8 @@ const transformsObject = { devtoolTransform, targetTransform, watchTransform, - watchOptionsTransform + watchOptionsTransform, + externalsTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index dd9195d8be7..04af7d78509 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -67,6 +67,15 @@ module.exports = class WebpackGenerator extends Generator { poll: 1000, ignored: '/node_modules/' } + this.configuration.webpackOptions.externals = { + jquery: 'jQuery', + subtract: ['./math', 'subtract'], + lodash : { + commonjs: "lodash", + amd: "lodash", + root: "_" // indicates global variable + } + } */ }); } From a2b9807df54c2c544c577f9b630b40b743ed1999 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 13:46:29 +0200 Subject: [PATCH 016/101] feat: ast for node --- lib/creator/transformations/index.js | 4 +++- lib/creator/transformations/node/node.js | 20 +++++++++++++++++++- lib/creator/yeoman/webpack-generator.js | 9 +++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index ffc85ccfdb6..9c2c57ab200 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -14,6 +14,7 @@ const targetTransform = require('./target/target'); const watchTransform = require('./watch/watch'); const watchOptionsTransform = require('./watch/watchOptions'); const externalsTransform = require('./externals/externals'); +const nodeTransform = require('./node/node'); /* * @function runTransform @@ -33,7 +34,8 @@ const transformsObject = { targetTransform, watchTransform, watchOptionsTransform, - externalsTransform + externalsTransform, + nodeTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index 8336fed5eda..4ae18b4ad0e 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -13,5 +13,23 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); + function createNodeProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'node', null)); + p.value.properties.filter(node => node.key.value === 'node').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.node).forEach( (webpackProp) => { + prop.value.properties.push( + utils.createProperty(j, webpackProp, webpackProperties.node[webpackProp]) + ); + }); + }); + } + } + if(webpackProperties['node'] && typeof(webpackProperties['node']) === 'object') { + return ast.find(j.ObjectExpression).filter(p => createNodeProperty(p)); + } else { + return ast; + } }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 04af7d78509..5d0d2af9e7d 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -76,6 +76,15 @@ module.exports = class WebpackGenerator extends Generator { root: "_" // indicates global variable } } + this.configuration.webpackOptions.node = { + console: false, + global: true, + process: true, + Buffer: true, + __filename: "mock", + __dirname: "mock", + setImmediate: true + } */ }); } From 9d5ebbe3fa49256b2ed0a977f8b97c3d8b8b0fab Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 14:18:25 +0200 Subject: [PATCH 017/101] feat: sat for performance --- lib/creator/transformations/index.js | 4 ++- .../performance/performance-types.js | 6 ++++ .../performance/performance.js | 31 ++++++++++++++++++- lib/creator/yeoman/webpack-generator.js | 9 ++++++ 4 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 lib/creator/transformations/performance/performance-types.js diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 9c2c57ab200..1f61dc3ff4b 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -15,6 +15,7 @@ const watchTransform = require('./watch/watch'); const watchOptionsTransform = require('./watch/watchOptions'); const externalsTransform = require('./externals/externals'); const nodeTransform = require('./node/node'); +const performanceTransform = require('./performance/performance'); /* * @function runTransform @@ -35,7 +36,8 @@ const transformsObject = { watchTransform, watchOptionsTransform, externalsTransform, - nodeTransform + nodeTransform, + performanceTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/performance/performance-types.js b/lib/creator/transformations/performance/performance-types.js new file mode 100644 index 00000000000..cbaf31dd699 --- /dev/null +++ b/lib/creator/transformations/performance/performance-types.js @@ -0,0 +1,6 @@ +module.exports = [ + 'hints', + 'maxEntrypointSize', + 'maxAssetSize', + 'assetFilter' +]; diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 8336fed5eda..5f1f32ea39a 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -1,4 +1,6 @@ const utils = require('../../../transformations/utils'); +const performanceTypes = require('./performance-types'); + /* safeTraverse, createProperty, @@ -13,5 +15,32 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); + function createPerformanceProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'performance', null)); + p.value.properties.filter(node => node.key.value === 'performance').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.performance).forEach( (webpackProp) => { + if(performanceTypes.includes(webpackProp)) { + if(Array.isArray(webpackProperties.performance[webpackProp])) { + throw new Error('Unknown Property', webpackProp); + } + else if(typeof(webpackProperties.performance[webpackProp]) === 'function') { + // function declr. + } else { + prop.value.properties.push(utils.createProperty(j, webpackProp, webpackProperties.performance[webpackProp])); + } + } else { + throw new Error('Unknown Property', webpackProp); + } + }); + }); + } + } + if(webpackProperties['performance'] && typeof(webpackProperties['performance']) === 'object') { + return ast.find(j.ObjectExpression).filter(p => createPerformanceProperty(p)); + } else { + return ast; + } }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 5d0d2af9e7d..5e70def6ebc 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -85,6 +85,15 @@ module.exports = class WebpackGenerator extends Generator { __dirname: "mock", setImmediate: true } + this.configuration.webpackOptions.performance = { + hints: "warning", + maxEntrypointSize: 400000, + maxAssetSize: 100000, + //buggy + assetFilter: function(assetFilename) { + return assetFilename.endsWith('.js'); + } + } */ }); } From 97c627d50264b76092de72339df186a565ff756c Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 16:54:56 +0200 Subject: [PATCH 018/101] feat: ast for stats --- lib/creator/transformations/index.js | 4 +- .../transformations/stats/stats-types.js | 31 +++++++++++++++ lib/creator/transformations/stats/stats.js | 39 ++++++++++++++++++- lib/creator/yeoman/webpack-generator.js | 1 + 4 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 lib/creator/transformations/stats/stats-types.js diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 1f61dc3ff4b..7c3abdfc478 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -16,6 +16,7 @@ const watchOptionsTransform = require('./watch/watchOptions'); const externalsTransform = require('./externals/externals'); const nodeTransform = require('./node/node'); const performanceTransform = require('./performance/performance'); +const statsTransform = require('./stats/stats'); /* * @function runTransform @@ -37,7 +38,8 @@ const transformsObject = { watchOptionsTransform, externalsTransform, nodeTransform, - performanceTransform + performanceTransform, + statsTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/stats/stats-types.js b/lib/creator/transformations/stats/stats-types.js new file mode 100644 index 00000000000..6a6dfd136a6 --- /dev/null +++ b/lib/creator/transformations/stats/stats-types.js @@ -0,0 +1,31 @@ +module.exports = [ + 'assets', + 'assetsSort', + 'cached', + 'cachedAssets', + 'children', + 'chunks', + 'chunkModules', + 'chunkOrigins', + 'chunksSort', + 'context', + 'colors', + 'depth', + 'entrypoints', + 'errors', + 'errorDetails', + 'exclude', + 'hash', + 'maxModules', + 'modules', + 'modulesSort', + 'performance', + 'providedExports', + 'publicPath', + 'reasons', + 'source', + 'timings', + 'usedExports', + 'version', + 'warnings' +]; diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index 8336fed5eda..c4c21bbe484 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -1,4 +1,5 @@ const utils = require('../../../transformations/utils'); +const statsTypes = require('./stats-types'); /* safeTraverse, createProperty, @@ -13,5 +14,41 @@ getRequire */ module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); + function createStatsProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'stats', null)); + p.value.properties.filter(node => node.key.value === 'stats').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.stats).forEach( (webpackProp) => { + if(statsTypes.includes(webpackProp)) { + if(Array.isArray(webpackProperties.stats[webpackProp])) { + const statsArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); + webpackProperties.stats[webpackProp].forEach( (n) => { + return statsArray.value.elements.push(j.literal(n)); + }); + prop.value.properties.push(statsArray); + } + else { + prop.value.properties.push(utils.createProperty(j, webpackProp, webpackProperties.stats[webpackProp])); + } + } else { + throw new Error('Unknown Property', webpackProp); + } + }); + }); + } + } + if(webpackProperties['stats'] && typeof(webpackProperties['stats']) === 'object') { + return ast.find(j.ObjectExpression).filter(p => createStatsProperty(p)); + } + else if(webpackProperties['stats'] && webpackProperties['stats'].length) { + return ast.find(j.ObjectExpression).filter(p => { + if(p.parent.value.type === 'AssignmentExpression') + return p.value.properties.push(utils.createProperty(j, 'stats', webpackProperties['stats'])); + + }); + } else { + return ast; + } }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 5e70def6ebc..ad4dd919a7b 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -94,6 +94,7 @@ module.exports = class WebpackGenerator extends Generator { return assetFilename.endsWith('.js'); } } + this.configuration.webpackOptions.stats = 'errors-only' */ }); } From 29d0c56337fdbe1991e90b3d1f7ea44fe2751793 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 17:25:57 +0200 Subject: [PATCH 019/101] feat: ast for other --- lib/creator/transformations/index.js | 10 +++++- lib/creator/transformations/other/amd.js | 35 ++++++++++++++++++++ lib/creator/transformations/other/bail.js | 26 +++++++++++++++ lib/creator/transformations/other/cache.js | 35 ++++++++++++++++++++ lib/creator/transformations/other/other.js | 17 ---------- lib/creator/transformations/other/profile.js | 26 +++++++++++++++ lib/creator/transformations/watch/watch.js | 2 +- lib/creator/yeoman/webpack-generator.js | 8 +++++ 8 files changed, 140 insertions(+), 19 deletions(-) create mode 100644 lib/creator/transformations/other/amd.js create mode 100644 lib/creator/transformations/other/bail.js create mode 100644 lib/creator/transformations/other/cache.js delete mode 100644 lib/creator/transformations/other/other.js create mode 100644 lib/creator/transformations/other/profile.js diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 7c3abdfc478..9a4a6a3202c 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -17,6 +17,10 @@ const externalsTransform = require('./externals/externals'); const nodeTransform = require('./node/node'); const performanceTransform = require('./performance/performance'); const statsTransform = require('./stats/stats'); +const amdTransform = require('./other/amd'); +const bailTransform = require('./other/bail'); +const cacheTransform = require('./other/cache'); +const profileTransform = require('./other/profile'); /* * @function runTransform @@ -39,7 +43,11 @@ const transformsObject = { externalsTransform, nodeTransform, performanceTransform, - statsTransform + statsTransform, + amdTransform, + bailTransform, + cacheTransform, + profileTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js new file mode 100644 index 00000000000..021ed7b92af --- /dev/null +++ b/lib/creator/transformations/other/amd.js @@ -0,0 +1,35 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + function createAMDProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'amd', null)); + p.value.properties.filter(node => node.key.value === 'amd').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.amd).forEach( (webpackProp) => { + prop.value.properties.push( + utils.createProperty(j, webpackProp, webpackProperties.amd[webpackProp]) + ); + }); + }); + } + } + if(webpackProperties['amd'] && typeof(webpackProperties['amd']) === 'object') { + return ast.find(j.ObjectExpression).filter(p => createAMDProperty(p)); + } else { + return ast; + } +}; diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js new file mode 100644 index 00000000000..b749969c6cf --- /dev/null +++ b/lib/creator/transformations/other/bail.js @@ -0,0 +1,26 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + function createBailProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'bail', webpackProperties['bail'])); + } + } + if(typeof(webpackProperties['bail']) === 'boolean') { + return ast.find(j.ObjectExpression).filter(p => createBailProperty(p)); + } else { + return ast; + } +}; diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js new file mode 100644 index 00000000000..a4e07e115f4 --- /dev/null +++ b/lib/creator/transformations/other/cache.js @@ -0,0 +1,35 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + function createCacheProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + // TODO: let people add obj by reference. + // webpackProperties['cache'] + p.value.properties.push(utils.createProperty(j, 'cache', 'TODO')); + } + } + if(typeof(webpackProperties['cache']) === 'boolean') { + return ast.find(j.ObjectExpression).filter(p => { + if(p.parent.value.type === 'AssignmentExpression') { + return p.value.properties.push(utils.createProperty(j, 'cache', webpackProperties['cache'])); + } + }); + } + else if(webpackProperties['cache'] && typeof(webpackProperties['cache']) === 'object') { + return ast.find(j.ObjectExpression).filter(p => createCacheProperty(p)); + } else { + return ast; + } +}; diff --git a/lib/creator/transformations/other/other.js b/lib/creator/transformations/other/other.js deleted file mode 100644 index 8336fed5eda..00000000000 --- a/lib/creator/transformations/other/other.js +++ /dev/null @@ -1,17 +0,0 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - -module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); -}; diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js new file mode 100644 index 00000000000..c70a729eea9 --- /dev/null +++ b/lib/creator/transformations/other/profile.js @@ -0,0 +1,26 @@ +const utils = require('../../../transformations/utils'); +/* +safeTraverse, +createProperty, +findPluginsByName, +findPluginsRootNodes, +createOrUpdatePluginByName, +findVariableToPlugin, +isType, +createLiteral, +findObjWithOneOfKeys, +getRequire +*/ + +module.exports = function(j, ast, webpackProperties) { + function createProfileProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(utils.createProperty(j, 'profile', webpackProperties['profile'])); + } + } + if(typeof(webpackProperties['profile']) === 'boolean') { + return ast.find(j.ObjectExpression).filter(p => createProfileProperty(p)); + } else { + return ast; + } +}; diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 2b9fb0676e8..8fd33ec58f3 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -18,7 +18,7 @@ module.exports = function(j, ast, webpackProperties) { return p.value.properties.push(utils.createProperty(j, 'watch', webpackProperties['watch'])); } } - if(typeof(webpackProperties['watch']) === 'boolean' && webpackProperties.hasOwnProperty('watch')) { + if(typeof(webpackProperties['watch']) === 'boolean') { return ast.find(j.ObjectExpression).filter(p => createWatchProperty(p)); } else { return ast; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index ad4dd919a7b..6ab7f581fd1 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -95,6 +95,14 @@ module.exports = class WebpackGenerator extends Generator { } } this.configuration.webpackOptions.stats = 'errors-only' + this.configuration.webpackOptions.amd = { + jQuery: true, + kQuery: false + } + this.configuration.webpackOptions.bail = true; + let SharedCache = {} + this.configuration.webpackOptions.cache = SharedCache + this.configuration.webpackOptions.profile = true */ }); } From bc6e1de97daee1558107e3e0cc0d2bcfcff6a5c1 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 9 Apr 2017 21:52:10 +0200 Subject: [PATCH 020/101] feat: allow multiple packages in CLI command --- lib/creator/index.js | 13 +++++++-- lib/utils/npm-packages-exists.js | 47 ++++++++++++++------------------ lib/utils/resolve-packages.js | 41 ++++++++++++++++------------ 3 files changed, 53 insertions(+), 48 deletions(-) diff --git a/lib/creator/index.js b/lib/creator/index.js index 9778b08fbe5..8f84dbe84fb 100644 --- a/lib/creator/index.js +++ b/lib/creator/index.js @@ -1,4 +1,5 @@ const yeoman = require('yeoman-environment'); +const Generator = require('yeoman-generator'); const path = require('path'); const defaultGenerator = require('./yeoman/webpack-generator'); const WebpackAdapter = require('./yeoman/webpack-adapter'); @@ -16,10 +17,16 @@ const runTransform = require('./transformations/index'); function creator(options) { const env = yeoman.createEnv(null, null, new WebpackAdapter()); - const generatorName = options ? replaceGeneratorName(path.basename(options)) : 'webpack-default-generator'; + const generatorName = options ? replaceGeneratorName(path.basename(options[0])) : 'webpack-default-generator'; if(options) { - const generatorName = replaceGeneratorName(path.basename(options)); - env.register(require.resolve(options), generatorName); + const WebpackGenerator = class extends Generator { + initializing() { + options.forEach( (path) => { + return this.composeWith(require.resolve(path)); + }); + } + }; + env.registerStub(WebpackGenerator, generatorName); } else { env.registerStub(defaultGenerator, 'webpack-default-generator'); } diff --git a/lib/utils/npm-packages-exists.js b/lib/utils/npm-packages-exists.js index 8748b1e47ac..020cf0bbd09 100644 --- a/lib/utils/npm-packages-exists.js +++ b/lib/utils/npm-packages-exists.js @@ -6,36 +6,29 @@ const resolvePackages = require('./resolve-packages'); * @function npmPackagesExists * * Loops through an array and checks if a package is registered -* on npm and throws an error if it is not from @checkEachPackage +* on npm and throws an error if it is not. * * @param { Array } pkg - Array of packages to check existence of -* @returns { Array } resolvePackages - Returns an process to install the pkg +* @returns { Array } resolvePackages - Returns an process to install the packages */ -module.exports = function npmPackagesExists(addons) { - return addons.map( pkg => checkEachPackage(pkg)); -}; -/* -* @function checkEachPackage -* -* Checks if a package is registered on npm and throws if it is not -* -* @param { Object } pkg - pkg to check existence of -* @returns { } resolvePackages - Returns an process to install the pkg -*/ - -function checkEachPackage(pkg) { - return npmExists(pkg).then( (moduleExists) => { - if(!moduleExists) { - Error.stackTraceLimit = 0; - throw new TypeError('Package isn\'t registered on npm.'); - } - if (moduleExists) { - return resolvePackages(pkg); - } - }).catch(err => { - console.error(err.stack || err); - process.exit(0); +module.exports = function npmPackagesExists(pkg) { + let acceptedPackages = []; + pkg.forEach( addon => { + npmExists(addon).then( (moduleExists) => { + if(!moduleExists) { + Error.stackTraceLimit = 0; + throw new TypeError('Package isn\'t registered on npm.'); + } + if (moduleExists) { + acceptedPackages.push(addon); + } + }).catch(err => { + console.error(err.stack || err); + process.exit(0); + }).then( () => { + if(acceptedPackages.length === pkg.length) return resolvePackages(acceptedPackages); + }); }); -} +}; diff --git a/lib/utils/resolve-packages.js b/lib/utils/resolve-packages.js index a892cc494d0..ab8b8561d55 100644 --- a/lib/utils/resolve-packages.js +++ b/lib/utils/resolve-packages.js @@ -36,31 +36,36 @@ function spawnChild(pkg) { /* * @function resolvePackages * -* Resolves the package after it is validated, later sending it to the creator -* to be validated +* Resolves and installs the packages, later sending them to @creator * -* @param { String } pkg - The dependency to be installed -* @returns { } creator - Validates the dependency and builds -* the webpack configuration +* @param { Array } pkg - The dependencies to be installed +* @returns { } creator - Builds +* a webpack configuration through yeoman or throws an error */ module.exports = function resolvePackages(pkg) { Error.stackTraceLimit = 30; - return processPromise(spawnChild(pkg)).then( () => { - try { - let loc = path.join('..', '..', 'node_modules', pkg); - return creator(loc); - } catch(err) { - console.log('Package wasn\'t validated correctly..'); - console.log('Submit an issue for', pkg, 'if this persists'); + + let packageLocations = []; + + pkg.forEach( (addon) => { + processPromise(spawnChild(addon)).then( () => { + try { + packageLocations.push(path.join('..', '..', 'node_modules', addon)); + } catch(err) { + console.log('Package wasn\'t validated correctly..'); + console.log('Submit an issue for', pkg, 'if this persists'); + console.log('\nReason: \n'); + console.error(chalk.bold.red(err)); + process.exit(1); + } + }).catch(err => { + console.log('Package Coudln\'t be installed, aborting..'); console.log('\nReason: \n'); console.error(chalk.bold.red(err)); process.exit(1); - } - }).catch(err => { - console.log('Package Coudln\'t be installed, aborting..'); - console.log('\nReason: \n'); - console.error(chalk.bold.red(err)); - process.exit(1); + }).then( () => { + if(packageLocations.length === pkg.length) return creator(packageLocations); + }); }); }; From 8153f2bec67c7935c6925a5a38264bed90e98cc3 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 10 Apr 2017 13:59:34 +0200 Subject: [PATCH 021/101] feat: allow dynamic entry points --- lib/creator/transformations/entry/entry.js | 29 ++++++++++++++++---- lib/creator/transformations/output/output.js | 14 +++++----- lib/creator/utils/arrowFunction.js | 7 +++++ lib/creator/yeoman/webpack-generator.js | 7 +++-- 4 files changed, 43 insertions(+), 14 deletions(-) create mode 100644 lib/creator/utils/arrowFunction.js diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 8782a15f514..2f3a85fd956 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,4 +1,5 @@ const utils = require('../../../transformations/utils'); +const jscodeshift = require('jscodeshift'); /* safeTraverse, createProperty, @@ -17,19 +18,37 @@ module.exports = function(j, ast, webpackProperties) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(utils.createProperty(j, 'entry', 'null')); p.value.properties.filter(node => node.key.value === 'entry').forEach( (prop) => { - if((webpackProperties['entry'] && webpackProperties['entry'].length) || typeof webpackProperties['entry'] === 'function') { + if((webpackProperties['entry'] && webpackProperties['entry'].length) && !webpackProperties['entry'].__paths) { prop.value.value = webpackProperties['entry']; + } + else if(webpackProperties['entry'].__paths) { + let funcDec = webpackProperties.entry.__paths[0].value.program.body[0]; + prop.value = funcDec; } else { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.entry).forEach( (webpackProps) => { - prop.value.properties.push( - utils.createProperty(j, webpackProps, webpackProperties.entry[webpackProps]) - ); + if(webpackProperties.entry[webpackProps].__paths) { + let funcDec = webpackProperties.entry[webpackProps].__paths[0].value.program.body[0]; + prop.value.properties.push( + utils.createProperty(j, webpackProps, 'null') + ); + prop.value.properties.filter(node => node.key.value === webpackProps).forEach( (funcProp) => { + funcProp.value = funcDec; + }); + } else { + prop.value.properties.push( + utils.createProperty(j, webpackProps, webpackProperties.entry[webpackProps]) + ); + } }); } }); } } - return ast.find(j.ObjectExpression).filter(p => createEntryProperty(p)); + if(webpackProperties['entry']) { + return ast.find(j.ObjectExpression).filter(p => createEntryProperty(p)); + } else { + return ast; + } }; diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 691b9e7aa45..cb8635cc225 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -2,12 +2,6 @@ const webpackOutputTypes = require('./output-types'); const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { - if(!webpackProperties['output']) { - return ast; - } else if(webpackProperties['output'].length) { - throw new Error('Supplying output with only no options is not supported.'); - } - function createOutputProperties(p) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(utils.createProperty(j, 'output', 'null')); @@ -24,5 +18,11 @@ module.exports = function(j, ast, webpackProperties) { }); } } - return ast.find(j.ObjectExpression).filter(p => createOutputProperties(p)); + if(!webpackProperties['output']) { + return ast; + } else if(webpackProperties['output'].length) { + throw new Error('Supplying output with only no options is not supported.'); + } else { + return ast.find(j.ObjectExpression).filter(p => createOutputProperties(p)); + } }; diff --git a/lib/creator/utils/arrowFunction.js b/lib/creator/utils/arrowFunction.js new file mode 100644 index 00000000000..d8bf0c1a6ad --- /dev/null +++ b/lib/creator/utils/arrowFunction.js @@ -0,0 +1,7 @@ +/* eslint-disable */ +const jscodeshift = require('jscodeshift'); + +// moving to webpack-addons later +module.exports = function(value) { + return jscodeshift("() => " + "'" + value + "'"); +} diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 6ab7f581fd1..52dbb6926ef 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -1,6 +1,6 @@ const Generator = require('yeoman-generator'); const Input = require('webpack-addons').Input; - +const parseArrow = require('../utils/arrowFunction'); module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { @@ -22,11 +22,14 @@ module.exports = class WebpackGenerator extends Generator { return this.prompt([Input('entry', 'What is the name of the entry point in your application?')]) .then( (answer) => { /* + let answeri = parseArrow(answer.entry); this.configuration.webpackOptions.entry = { vendor: 'home', js: 'yes', - ohye: 'no' + ohye: 'no', + nana: answeri }; + this.configuration.webpackOptions.entry = answeri; this.configuration.webpackOptions.output.filename = 'hello'; this.configuration.webpackOptions.output.path = 'dist/assets'; this.configuration.webpackOptions.output.pathinfo = true; From 3c7b0211cd3eccac8c9e651fd2cae8a8efdf38be Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 10 Apr 2017 14:17:54 +0200 Subject: [PATCH 022/101] feat: allow promises as entry points --- lib/creator/utils/addonsUtils.js | 21 +++++++++++++++++++++ lib/creator/utils/arrowFunction.js | 7 ------- lib/creator/yeoman/webpack-generator.js | 5 +++-- 3 files changed, 24 insertions(+), 9 deletions(-) create mode 100644 lib/creator/utils/addonsUtils.js delete mode 100644 lib/creator/utils/arrowFunction.js diff --git a/lib/creator/utils/addonsUtils.js b/lib/creator/utils/addonsUtils.js new file mode 100644 index 00000000000..28ec0c4ff8f --- /dev/null +++ b/lib/creator/utils/addonsUtils.js @@ -0,0 +1,21 @@ +/* eslint-disable */ +const jscodeshift = require('jscodeshift'); + +// moving to webpack-addons later +function arrowFunction(value) { + return jscodeshift("() => " + "'" + value + "'"); +}; +function dynamicPromise(arr) { + if(Array.isArray(arr)) { + return jscodeshift("() => new Promise((resolve) => resolve([" + arr.map( (n) => { + return "'" + n + "'" + }) + "]))"); + } else { + return jscodeshift("() => new Promise((resolve) => resolve(" + "'" + arr + "'" + "))"); + } +}; + +module.exports = { + arrowFunction, + dynamicPromise +}; diff --git a/lib/creator/utils/arrowFunction.js b/lib/creator/utils/arrowFunction.js deleted file mode 100644 index d8bf0c1a6ad..00000000000 --- a/lib/creator/utils/arrowFunction.js +++ /dev/null @@ -1,7 +0,0 @@ -/* eslint-disable */ -const jscodeshift = require('jscodeshift'); - -// moving to webpack-addons later -module.exports = function(value) { - return jscodeshift("() => " + "'" + value + "'"); -} diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 52dbb6926ef..b44d6b09420 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -1,6 +1,7 @@ const Generator = require('yeoman-generator'); const Input = require('webpack-addons').Input; -const parseArrow = require('../utils/arrowFunction'); +const parseArrow = require('../utils/addonsUtils').arrowFunction; +const parsePromise = require('../utils/addonsUtils').dynamicPromise; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { @@ -22,7 +23,7 @@ module.exports = class WebpackGenerator extends Generator { return this.prompt([Input('entry', 'What is the name of the entry point in your application?')]) .then( (answer) => { /* - let answeri = parseArrow(answer.entry); + let answeri = parsePromise(answer.entry); this.configuration.webpackOptions.entry = { vendor: 'home', js: 'yes', From e3d522b361030379317af3383d88fc60505a4066 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 10 Apr 2017 15:00:19 +0200 Subject: [PATCH 023/101] feat: function decl for resolve.cachePredictate --- lib/creator/transformations/resolve/resolve.js | 8 ++++++-- lib/creator/utils/addonsUtils.js | 6 +++++- lib/creator/yeoman/webpack-generator.js | 2 ++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index a35160f93c1..cbb3d7fec67 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -35,8 +35,12 @@ module.exports = function(j, ast, webpackProperties) { else if(typeof(webpackProperties.resolve[webpackProp]) === 'boolean') { let boolExp = j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.resolve[webpackProp])); prop.value.properties.push(boolExp); - } else if(typeof(webpackProperties.resolve[webpackProp]) === 'function') { - // function declr. + } else if(webpackProperties.resolve[webpackProp].__paths) { + let funcDec = webpackProperties.resolve[webpackProp].__paths[0].value.program.body[0]; + prop.value.properties.push(utils.createProperty(j, webpackProp, 'null')); + prop.value.properties.filter(node => node.key.value === webpackProp).forEach( (funcProp) => { + funcProp.value = funcDec; + }); } else { prop.value.properties.push(utils.createProperty(j, webpackProp, null)); diff --git a/lib/creator/utils/addonsUtils.js b/lib/creator/utils/addonsUtils.js index 28ec0c4ff8f..108ebf9038b 100644 --- a/lib/creator/utils/addonsUtils.js +++ b/lib/creator/utils/addonsUtils.js @@ -5,6 +5,9 @@ const jscodeshift = require('jscodeshift'); function arrowFunction(value) { return jscodeshift("() => " + "'" + value + "'"); }; +function regularFunction(value, funcName) { + return jscodeshift("function " + funcName + "() {\n return " + "'" + value + "'" + "\n}"); +}; function dynamicPromise(arr) { if(Array.isArray(arr)) { return jscodeshift("() => new Promise((resolve) => resolve([" + arr.map( (n) => { @@ -17,5 +20,6 @@ function dynamicPromise(arr) { module.exports = { arrowFunction, - dynamicPromise + dynamicPromise, + regularFunction }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index b44d6b09420..feee4476453 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -2,6 +2,7 @@ const Generator = require('yeoman-generator'); const Input = require('webpack-addons').Input; const parseArrow = require('../utils/addonsUtils').arrowFunction; const parsePromise = require('../utils/addonsUtils').dynamicPromise; +const parseFunction = require('../utils/addonsUtils').regularFunction; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { @@ -63,6 +64,7 @@ module.exports = class WebpackGenerator extends Generator { } this.configuration.webpackOptions.resolve.plugins = []; this.configuration.webpackOptions.resolve.symlinks = true; + this.configuration.webpackOptions.resolve.cachePredicate = parseFunction(true, 'cachePredicate') this.configuration.webpackOptions.devtool = 'eval' this.configuration.webpackOptions.target = 'async-node' this.configuration.webpackOptions.watch = true; From 2f1e89120f056ec0fff5376c57e715a7dce795aa Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 10 Apr 2017 15:10:26 +0200 Subject: [PATCH 024/101] feat: allow function for performance.assetFilter --- lib/creator/transformations/performance/performance.js | 8 ++++++-- lib/creator/utils/addonsUtils.js | 6 +++++- lib/creator/yeoman/webpack-generator.js | 5 ++--- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 5f1f32ea39a..99c9951616d 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -26,8 +26,12 @@ module.exports = function(j, ast, webpackProperties) { if(Array.isArray(webpackProperties.performance[webpackProp])) { throw new Error('Unknown Property', webpackProp); } - else if(typeof(webpackProperties.performance[webpackProp]) === 'function') { - // function declr. + else if(webpackProperties.performance[webpackProp].__paths) { + let funcDec = webpackProperties.performance[webpackProp].__paths[0].value.program.body[0]; + prop.value.properties.push(utils.createProperty(j, webpackProp, 'null')); + prop.value.properties.filter(node => node.key.value === webpackProp).forEach( (funcProp) => { + funcProp.value = funcDec; + }); } else { prop.value.properties.push(utils.createProperty(j, webpackProp, webpackProperties.performance[webpackProp])); } diff --git a/lib/creator/utils/addonsUtils.js b/lib/creator/utils/addonsUtils.js index 108ebf9038b..7d50628a483 100644 --- a/lib/creator/utils/addonsUtils.js +++ b/lib/creator/utils/addonsUtils.js @@ -17,9 +17,13 @@ function dynamicPromise(arr) { return jscodeshift("() => new Promise((resolve) => resolve(" + "'" + arr + "'" + "))"); } }; +function assetFilterFunction(value) { + return jscodeshift("function assetFilter" + "(assetFilename) {\n return assetFilename.endsWith(" + "'" + "." + value + "'" + ");\n}"); +}; module.exports = { arrowFunction, dynamicPromise, - regularFunction + regularFunction, + assetFilterFunction }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index feee4476453..f8c4b9aff11 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -3,6 +3,7 @@ const Input = require('webpack-addons').Input; const parseArrow = require('../utils/addonsUtils').arrowFunction; const parsePromise = require('../utils/addonsUtils').dynamicPromise; const parseFunction = require('../utils/addonsUtils').regularFunction; +const assetFilterFunction = require('../utils/addonsUtils').assetFilterFunction; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { @@ -96,9 +97,7 @@ module.exports = class WebpackGenerator extends Generator { maxEntrypointSize: 400000, maxAssetSize: 100000, //buggy - assetFilter: function(assetFilename) { - return assetFilename.endsWith('.js'); - } + assetFilter: assetFilterFunction('js') } this.configuration.webpackOptions.stats = 'errors-only' this.configuration.webpackOptions.amd = { From 9a230b8be544243ff46eb71845615a9f0f09de09 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 10 Apr 2017 15:49:12 +0200 Subject: [PATCH 025/101] feat: allow regex and functions in external prop --- .../transformations/externals/externals.js | 19 +++++++++++++++---- lib/creator/utils/addonsUtils.js | 12 +++++++++++- lib/creator/yeoman/webpack-generator.js | 10 +++++++++- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 68ea996f073..979d41c6644 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -15,7 +15,15 @@ getRequire module.exports = function(j, ast, webpackProperties) { function createExternalProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'externals', null)); + if(webpackProperties.externals instanceof RegExp) { + return p.value.properties.push(utils.createProperty(j, 'externals', webpackProperties.externals)); + } + else if(webpackProperties.externals.__paths) { + let RegExpDec = webpackProperties.externals.__paths[0].value.program.body[0].expression.rawValue; + return p.value.properties.push(utils.createProperty(j, 'externals', RegExpDec)); + } else { + p.value.properties.push(utils.createProperty(j, 'externals', null)); + } p.value.properties.filter(node => node.key.value === 'externals').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; @@ -28,12 +36,15 @@ module.exports = function(j, ast, webpackProperties) { }); prop.value.properties.push(externalArray); } - else if(typeof(webpackProperties.externals[webpackProp]) === 'function') { - // function declr. - } else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { prop.value.properties.push(utils.createProperty(j, webpackProp, webpackProperties.externals[webpackProp])); } + else if(webpackProperties.externals[webpackProp].__paths) { + let funcDec = webpackProperties.externals[webpackProp].__paths[0].value.program.body[0]; + prop.value.type = 'ArrayExpression'; + prop.value.elements = []; + prop.value.elements.push(funcDec); + } else { prop.value.properties.push(utils.createProperty(j, webpackProp, null)); prop.value.properties.forEach( (externalProp) => { diff --git a/lib/creator/utils/addonsUtils.js b/lib/creator/utils/addonsUtils.js index 7d50628a483..e4a603eab9c 100644 --- a/lib/creator/utils/addonsUtils.js +++ b/lib/creator/utils/addonsUtils.js @@ -20,10 +20,20 @@ function dynamicPromise(arr) { function assetFilterFunction(value) { return jscodeshift("function assetFilter" + "(assetFilename) {\n return assetFilename.endsWith(" + "'" + "." + value + "'" + ");\n}"); }; +function externalRegExp(regexp) { + return jscodeshift("\n function externalRegExp(context, request, callback) {\n if (" + + "/" + regexp + "/.test(request)){" + "\n" + " return callback(null, 'commonjs ' + request);\n}\n" + + "callback();\n}") +}; +function pureRegExp(regexp) { + return jscodeshift(regexp) +}; module.exports = { arrowFunction, dynamicPromise, regularFunction, - assetFilterFunction + assetFilterFunction, + externalRegExp, + pureRegExp }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index f8c4b9aff11..019f6775392 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -4,7 +4,8 @@ const parseArrow = require('../utils/addonsUtils').arrowFunction; const parsePromise = require('../utils/addonsUtils').dynamicPromise; const parseFunction = require('../utils/addonsUtils').regularFunction; const assetFilterFunction = require('../utils/addonsUtils').assetFilterFunction; - +const externalRegExp = require('../utils/addonsUtils').externalRegExp; +const pureRegExp = require('../utils/addonsUtils').pureRegExp; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { super(args, opts); @@ -74,6 +75,7 @@ module.exports = class WebpackGenerator extends Generator { poll: 1000, ignored: '/node_modules/' } + this.configuration.webpackOptions.externals = { jquery: 'jQuery', subtract: ['./math', 'subtract'], @@ -83,6 +85,12 @@ module.exports = class WebpackGenerator extends Generator { root: "_" // indicates global variable } } + + this.configuration.webpackOptions.externals = [ + externalRegExp('^.js$') + ] + + this.configuration.webpackOptions.externals = /^(jquery|\$)$/i this.configuration.webpackOptions.node = { console: false, global: true, From f87aa2b92f7091fae3a6138e952f3dd7220eba80 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 10 Apr 2017 16:12:16 +0200 Subject: [PATCH 026/101] feat: regexp for outputPrefix --- lib/creator/transformations/output/output.js | 13 ++++++++++--- lib/creator/yeoman/webpack-generator.js | 3 +-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index cb8635cc225..2654e800270 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -10,9 +10,16 @@ module.exports = function(j, ast, webpackProperties) { prop.value.properties = []; Object.keys(webpackProperties.output).forEach( (webpackProp) => { if(webpackOutputTypes.includes(webpackProp)) { - prop.value.properties.push( - utils.createProperty(j, webpackProp, webpackProperties.output[webpackProp]) - ); + if(webpackProperties.output[webpackProp].__paths) { + let RegExpDec = webpackProperties.output[webpackProp].__paths[0].value.program.body[0].expression; + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.literal(RegExpDec.value)) + ); + } else { + prop.value.properties.push( + utils.createProperty(j, webpackProp, webpackProperties.output[webpackProp]) + ); + } } }); }); diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 019f6775392..bd6975fabcb 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -40,8 +40,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.webpackOptions.output.publicPath = "https://newbie.com" this.configuration.webpackOptions.output.sourceMapFilename = "[name].map" - // buggy - this.configuration.webpackOptions.output.sourcePrefix = `${"\t"}` + this.configuration.webpackOptions.output.sourcePrefix = pureRegExp("'\t'") this.configuration.webpackOptions.output.umdNamedDefine = true; this.configuration.webpackOptions.output.strictModuleExceptionHandling = true; From 009c0e740b73c51656be74a9584cc5c950ee9dc6 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 10 Apr 2017 16:47:52 +0200 Subject: [PATCH 027/101] feat: use property without strings --- .../transformations/context/context.js | 16 +--------- .../transformations/devtool/devtool.js | 16 +--------- lib/creator/transformations/entry/entry.js | 25 ++++------------ .../transformations/externals/externals.js | 30 +++++-------------- lib/creator/transformations/node/node.js | 20 ++----------- lib/creator/transformations/other/amd.js | 20 ++----------- lib/creator/transformations/other/bail.js | 16 +--------- lib/creator/transformations/other/cache.js | 18 ++--------- lib/creator/transformations/other/profile.js | 16 +--------- lib/creator/transformations/output/output.js | 7 ++--- .../performance/performance.js | 24 ++++----------- .../transformations/resolve/resolve.js | 27 +++++------------ lib/creator/transformations/stats/stats.js | 21 +++---------- lib/creator/transformations/target/target.js | 16 +--------- lib/creator/transformations/watch/watch.js | 16 +--------- .../transformations/watch/watchOptions.js | 20 ++----------- 16 files changed, 49 insertions(+), 259 deletions(-) diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 97fb9e97a52..ad736d23c5b 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,21 +1,7 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createContextProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(utils.createProperty(j, 'context', webpackProperties['context'])); + return p.value.properties.push(j.property('init', j.identifier('context'), j.literal(webpackProperties['context']))); } } if(webpackProperties['context'] && webpackProperties['context'].length) { diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index b48553a5cd7..1e1aac99af2 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,21 +1,7 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createDevToolProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(utils.createProperty(j, 'devtool', webpackProperties['devtool'])); + return p.value.properties.push(j.property('init', j.identifier('devtool'), j.literal(webpackProperties['devtool']))); } } if(webpackProperties['devtool'] && webpackProperties['devtool'].length) { diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 2f3a85fd956..accf730e93c 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,23 +1,8 @@ -const utils = require('../../../transformations/utils'); -const jscodeshift = require('jscodeshift'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createEntryProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'entry', 'null')); - p.value.properties.filter(node => node.key.value === 'entry').forEach( (prop) => { + p.value.properties.push(j.property('init', j.identifier('entry'), j.literal('null'))); + p.value.properties.filter(node => node.key.name === 'entry').forEach( (prop) => { if((webpackProperties['entry'] && webpackProperties['entry'].length) && !webpackProperties['entry'].__paths) { prop.value.value = webpackProperties['entry']; } @@ -31,14 +16,14 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties.entry[webpackProps].__paths) { let funcDec = webpackProperties.entry[webpackProps].__paths[0].value.program.body[0]; prop.value.properties.push( - utils.createProperty(j, webpackProps, 'null') + j.property('init', j.identifier(webpackProps), j.literal('null')) ); - prop.value.properties.filter(node => node.key.value === webpackProps).forEach( (funcProp) => { + prop.value.properties.filter(node => node.key.name === webpackProps).forEach( (funcProp) => { funcProp.value = funcDec; }); } else { prop.value.properties.push( - utils.createProperty(j, webpackProps, webpackProperties.entry[webpackProps]) + j.property('init', j.identifier(webpackProps), j.literal(webpackProperties.entry[webpackProps])) ); } }); diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 979d41c6644..234dcadfc92 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -1,30 +1,16 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createExternalProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { if(webpackProperties.externals instanceof RegExp) { - return p.value.properties.push(utils.createProperty(j, 'externals', webpackProperties.externals)); + return p.value.properties.push(j.property('init', j.identifier('externals'), j.literal(webpackProperties.externals))); } else if(webpackProperties.externals.__paths) { let RegExpDec = webpackProperties.externals.__paths[0].value.program.body[0].expression.rawValue; - return p.value.properties.push(utils.createProperty(j, 'externals', RegExpDec)); + return p.value.properties.push(j.property('init', j.identifier('externals'), j.literal(RegExpDec))); } else { - p.value.properties.push(utils.createProperty(j, 'externals', null)); + p.value.properties.push(j.property('init', j.identifier('externals'), j.literal('null'))); } - p.value.properties.filter(node => node.key.value === 'externals').forEach( (prop) => { + p.value.properties.filter(node => node.key.name === 'externals').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.externals).forEach( (webpackProp) => { @@ -37,7 +23,7 @@ module.exports = function(j, ast, webpackProperties) { prop.value.properties.push(externalArray); } else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { - prop.value.properties.push(utils.createProperty(j, webpackProp, webpackProperties.externals[webpackProp])); + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.externals[webpackProp]))); } else if(webpackProperties.externals[webpackProp].__paths) { let funcDec = webpackProperties.externals[webpackProp].__paths[0].value.program.body[0]; @@ -46,9 +32,9 @@ module.exports = function(j, ast, webpackProperties) { prop.value.elements.push(funcDec); } else { - prop.value.properties.push(utils.createProperty(j, webpackProp, null)); + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); prop.value.properties.forEach( (externalProp) => { - if(externalProp.key.value === webpackProp) { + if(externalProp.key.name === webpackProp) { externalProp.value.type = 'ObjectExpression'; externalProp.value.properties = []; Object.keys(webpackProperties.externals[webpackProp]).forEach( (subProps) => { @@ -60,7 +46,7 @@ module.exports = function(j, ast, webpackProperties) { externalProp.value.properties.push(subExternalArray); } else { externalProp.value.properties.push( - utils.createProperty(j, subProps, webpackProperties.externals[webpackProp][subProps]) + j.createProperty('init', j.identifier(subProps), j.literal(webpackProperties.externals[webpackProp][subProps])) ); } }); diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index 4ae18b4ad0e..20da35ab0c1 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -1,27 +1,13 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createNodeProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'node', null)); - p.value.properties.filter(node => node.key.value === 'node').forEach( (prop) => { + p.value.properties.push(j.property('init', j.identifier('node'), j.literal('null'))); + p.value.properties.filter(node => node.key.name === 'node').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.node).forEach( (webpackProp) => { prop.value.properties.push( - utils.createProperty(j, webpackProp, webpackProperties.node[webpackProp]) + j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.node[webpackProp])) ); }); }); diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index 021ed7b92af..11aaa38b489 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -1,27 +1,13 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createAMDProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'amd', null)); - p.value.properties.filter(node => node.key.value === 'amd').forEach( (prop) => { + p.value.properties.push(j.property('init', j.identifier('amd'), j.literal('null'))); + p.value.properties.filter(node => node.key.name === 'amd').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.amd).forEach( (webpackProp) => { prop.value.properties.push( - utils.createProperty(j, webpackProp, webpackProperties.amd[webpackProp]) + j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.amd[webpackProp])) ); }); }); diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index b749969c6cf..a5db0c96263 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,21 +1,7 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createBailProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'bail', webpackProperties['bail'])); + p.value.properties.push(j.property('init', j.identifier('bail'), j.literal(webpackProperties['bail']))); } } if(typeof(webpackProperties['bail']) === 'boolean') { diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index a4e07e115f4..b14a22bde55 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,29 +1,15 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createCacheProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { // TODO: let people add obj by reference. // webpackProperties['cache'] - p.value.properties.push(utils.createProperty(j, 'cache', 'TODO')); + return p.value.properties.push(j.property('init', j.identifier('cache'), j.literal('TODO'))); } } if(typeof(webpackProperties['cache']) === 'boolean') { return ast.find(j.ObjectExpression).filter(p => { if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(utils.createProperty(j, 'cache', webpackProperties['cache'])); + return p.value.properties.push(j.property('init', j.identifier('cache'), j.literal(webpackProperties['cache']))); } }); } diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index c70a729eea9..ef59bb3ac9c 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,21 +1,7 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createProfileProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'profile', webpackProperties['profile'])); + p.value.properties.push(j.property('init', j.identifier('profile'), j.literal(webpackProperties['profile']))); } } if(typeof(webpackProperties['profile']) === 'boolean') { diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 2654e800270..3650cb5899e 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -1,11 +1,10 @@ const webpackOutputTypes = require('./output-types'); -const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { function createOutputProperties(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'output', 'null')); - p.value.properties.filter( node => node.key.value === 'output').forEach( (prop) => { + p.value.properties.push(j.property('init', j.identifier('output'), j.literal('null'))); + p.value.properties.filter( node => node.key.name === 'output').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.output).forEach( (webpackProp) => { @@ -17,7 +16,7 @@ module.exports = function(j, ast, webpackProperties) { ); } else { prop.value.properties.push( - utils.createProperty(j, webpackProp, webpackProperties.output[webpackProp]) + j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.output[webpackProp])) ); } } diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 99c9951616d..d84bbc2e879 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -1,24 +1,10 @@ -const utils = require('../../../transformations/utils'); const performanceTypes = require('./performance-types'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createPerformanceProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'performance', null)); - p.value.properties.filter(node => node.key.value === 'performance').forEach( (prop) => { + p.value.properties.push(j.property('init', j.identifier('performance'), j.literal('null'))); + p.value.properties.filter(node => node.key.name === 'performance').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.performance).forEach( (webpackProp) => { @@ -28,12 +14,12 @@ module.exports = function(j, ast, webpackProperties) { } else if(webpackProperties.performance[webpackProp].__paths) { let funcDec = webpackProperties.performance[webpackProp].__paths[0].value.program.body[0]; - prop.value.properties.push(utils.createProperty(j, webpackProp, 'null')); - prop.value.properties.filter(node => node.key.value === webpackProp).forEach( (funcProp) => { + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); + prop.value.properties.filter(node => node.key.name === webpackProp).forEach( (funcProp) => { funcProp.value = funcDec; }); } else { - prop.value.properties.push(utils.createProperty(j, webpackProp, webpackProperties.performance[webpackProp])); + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.performance[webpackProp]))); } } else { throw new Error('Unknown Property', webpackProp); diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index cbb3d7fec67..85351f5c92b 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -1,25 +1,12 @@ -const utils = require('../../../transformations/utils'); const resolveTypes = require('./resolve-types'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ module.exports = function(j, ast, webpackProperties) { function createResolveProperties(p) { if(webpackProperties['resolve']) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'resolve', 'null')); + p.value.properties.push(j.property('init', j.identifier('resolve'), j.literal('null'))); } - p.value.properties.filter(node => node.key.value === 'resolve').forEach( (prop) => { + p.value.properties.filter(node => node.key.name === 'resolve').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.resolve).forEach( (webpackProp) => { @@ -37,15 +24,15 @@ module.exports = function(j, ast, webpackProperties) { prop.value.properties.push(boolExp); } else if(webpackProperties.resolve[webpackProp].__paths) { let funcDec = webpackProperties.resolve[webpackProp].__paths[0].value.program.body[0]; - prop.value.properties.push(utils.createProperty(j, webpackProp, 'null')); - prop.value.properties.filter(node => node.key.value === webpackProp).forEach( (funcProp) => { + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); + prop.value.properties.filter(node => node.key.name === webpackProp).forEach( (funcProp) => { funcProp.value = funcDec; }); } else { - prop.value.properties.push(utils.createProperty(j, webpackProp, null)); + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); prop.value.properties.forEach( (resolveProp) => { - if(resolveProp.key.value === webpackProp) { + if(resolveProp.key.name === webpackProp) { resolveProp.value.type = 'ObjectExpression'; resolveProp.value.properties = []; Object.keys(webpackProperties.resolve[webpackProp]).forEach( (aliasProps) => { @@ -57,7 +44,7 @@ module.exports = function(j, ast, webpackProperties) { resolveProp.value.properties.push(resolveLoaderArray); } else { resolveProp.value.properties.push( - utils.createProperty(j, aliasProps, webpackProperties.resolve[webpackProp][aliasProps]) + j.property('init', j.identifier(aliasProps), j.literal(webpackProperties.resolve[webpackProp][aliasProps])) ); } }); diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index c4c21bbe484..e2cf090f335 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -1,23 +1,10 @@ -const utils = require('../../../transformations/utils'); const statsTypes = require('./stats-types'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ module.exports = function(j, ast, webpackProperties) { function createStatsProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'stats', null)); - p.value.properties.filter(node => node.key.value === 'stats').forEach( (prop) => { + p.value.properties.push(j.property('init', j.identifier('stats'), j.literal('null'))); + p.value.properties.filter(node => node.key.name === 'stats').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.stats).forEach( (webpackProp) => { @@ -30,7 +17,7 @@ module.exports = function(j, ast, webpackProperties) { prop.value.properties.push(statsArray); } else { - prop.value.properties.push(utils.createProperty(j, webpackProp, webpackProperties.stats[webpackProp])); + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.stats[webpackProp]))); } } else { throw new Error('Unknown Property', webpackProp); @@ -45,7 +32,7 @@ module.exports = function(j, ast, webpackProperties) { else if(webpackProperties['stats'] && webpackProperties['stats'].length) { return ast.find(j.ObjectExpression).filter(p => { if(p.parent.value.type === 'AssignmentExpression') - return p.value.properties.push(utils.createProperty(j, 'stats', webpackProperties['stats'])); + return p.value.properties.push(j.property('init', j.identifier('stats'), j.literal(webpackProperties['stats']))); }); } else { diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 6459ef1b8e3..596ea525041 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,21 +1,7 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createTargetProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(utils.createProperty(j, 'target', webpackProperties['target'])); + return p.value.properties.push(j.property('init', j.identifier('target'), j.literal(webpackProperties['target']))); } } if(webpackProperties['target'] && webpackProperties['target'].length) { diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 8fd33ec58f3..ed868995912 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,21 +1,7 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createWatchProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(utils.createProperty(j, 'watch', webpackProperties['watch'])); + return p.value.properties.push(j.property('init', j.identifier('watch'), j.literal(webpackProperties['watch']))); } } if(typeof(webpackProperties['watch']) === 'boolean') { diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index 6cd88a8717a..741eb864051 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -1,30 +1,16 @@ -const utils = require('../../../transformations/utils'); const watchOptionTypes = require('./watchOptions-types'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - module.exports = function(j, ast, webpackProperties) { function createWatchOptionsProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(utils.createProperty(j, 'watchOptions', null)); - p.value.properties.filter(node => node.key.value === 'watchOptions').forEach( (prop) => { + p.value.properties.push(j.property('init', j.identifier('watchOptions'), j.literal('null'))); + p.value.properties.filter(node => node.key.name === 'watchOptions').forEach( (prop) => { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { if(watchOptionTypes.includes(watchOption)) { prop.value.properties.push( - utils.createProperty(j, watchOption, webpackProperties['watchOptions'][watchOption]) + j.property('init', j.identifier(watchOption), j.literal(webpackProperties['watchOptions'][watchOption])) ); } else { throw new Error('Unknown Property', watchOption); From 471fa26bef7df2fbe50f11b48fff31b6684d2233 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 10 Apr 2017 20:32:56 +0200 Subject: [PATCH 028/101] feat: allow regex for unsafeCache --- lib/creator/yeoman/webpack-generator.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index bd6975fabcb..53b7c26d95d 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -56,7 +56,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.webpackOptions.resolve.mainFields = ["mod", 'ho', 'bo'] this.configuration.webpackOptions.resolve.mainFiles = ["index"] this.configuration.webpackOptions.resolve.modules = ["Heo"] - this.configuration.webpackOptions.resolve.unsafeCache = true + this.configuration.webpackOptions.resolve.unsafeCache = pureRegExp("'/src\\/utilities/'") this.configuration.webpackOptions.resolve.resolveLoader = { modules: ["node_modules"], extensions: [".js", ".json"], @@ -103,7 +103,7 @@ module.exports = class WebpackGenerator extends Generator { hints: "warning", maxEntrypointSize: 400000, maxAssetSize: 100000, - //buggy + assetFilter: assetFilterFunction('js') } this.configuration.webpackOptions.stats = 'errors-only' From 04add9b32773e85aeb503ca17dafde7381e337c5 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 11 Apr 2017 00:06:55 +0200 Subject: [PATCH 029/101] feat: ast for module --- .../transformations/devServer/dev-server.js | 17 -- lib/creator/transformations/index.js | 4 +- .../transformations/module/module-types.js | 17 ++ lib/creator/transformations/module/module.js | 147 ++++++++++++++++++ lib/creator/yeoman/webpack-generator.js | 69 ++++++++ 5 files changed, 236 insertions(+), 18 deletions(-) delete mode 100644 lib/creator/transformations/devServer/dev-server.js create mode 100644 lib/creator/transformations/module/module-types.js create mode 100644 lib/creator/transformations/module/module.js diff --git a/lib/creator/transformations/devServer/dev-server.js b/lib/creator/transformations/devServer/dev-server.js deleted file mode 100644 index 8336fed5eda..00000000000 --- a/lib/creator/transformations/devServer/dev-server.js +++ /dev/null @@ -1,17 +0,0 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ - -module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); -}; diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 9a4a6a3202c..8cde92c971e 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -21,6 +21,7 @@ const amdTransform = require('./other/amd'); const bailTransform = require('./other/bail'); const cacheTransform = require('./other/cache'); const profileTransform = require('./other/profile'); +const moduleTransform = require('./module/module'); /* * @function runTransform @@ -47,7 +48,8 @@ const transformsObject = { amdTransform, bailTransform, cacheTransform, - profileTransform + profileTransform, + moduleTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/module/module-types.js b/lib/creator/transformations/module/module-types.js new file mode 100644 index 00000000000..f0b74008523 --- /dev/null +++ b/lib/creator/transformations/module/module-types.js @@ -0,0 +1,17 @@ +module.exports = [ + 'enforce', + 'exclude', + 'include', + 'issuer', + 'loader', + 'loaders', + 'oneOf', + 'options', + 'query', + 'parser', + 'resource', + 'resourceQuery', + 'rules', + 'test', + 'use' +]; diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js new file mode 100644 index 00000000000..278be10a32e --- /dev/null +++ b/lib/creator/transformations/module/module.js @@ -0,0 +1,147 @@ +const webpackModuleTypes = require('./module-types'); + +module.exports = function(j, ast, webpackProperties) { + function createModuleProperties(p) { + if(p.parent.value.type === 'AssignmentExpression') { + p.value.properties.push(j.property('init', j.identifier('module'), j.literal('null'))); + p.value.properties.filter( node => node.key.name === 'module').forEach( (prop) => { + prop.value.type = 'ObjectExpression'; + prop.value.properties = []; + Object.keys(webpackProperties.module).forEach( (webpackProp) => { + if(['noParse', 'rules'].includes(webpackProp)) { + if(webpackProperties.module[webpackProp].__paths) { + let RegExpDec = webpackProperties.module[webpackProp].__paths[0].value.program.body[0].expression; + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.literal(RegExpDec.value)) + ); + } + else if(Array.isArray(webpackProperties.module[webpackProp])) { + const moduleArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); + prop.value.properties.push(moduleArray); + let seen = -1; + webpackProperties.module[webpackProp].forEach( (subProps) => { + prop.value.properties.filter(n => n.key.name === webpackProp).forEach( moduleProp => { + for(let key in subProps) { + if(webpackModuleTypes.includes(key)) { + if(subProps[key].__paths && key === 'test') { + moduleProp.value.elements.push(j.objectExpression([])); + seen += 1; + moduleProp.value.elements[seen].properties.push( + j.property( + 'init', + j.identifier(key), + j.literal( + subProps[key].__paths[0].value.program.body[0].expression.rawValue + ) + ) + ); + } + if(key === 'enforce') { + moduleProp.value.elements[seen].properties.push( + j.property('init', j.identifier(key), j.literal(subProps[key])) + ); + } + if(key === 'loader') { + moduleProp.value.elements[seen].properties.push( + j.property('init', j.identifier(key), j.literal(subProps[key])) + ); + } + if(key === 'options') { + let optionVal = j.property('init', j.identifier(key), j.identifier('presets')); + optionVal.value.type = 'ObjectExpression'; + optionVal.value.properties = []; + + Object.keys(subProps[key]).forEach( (optionProperty) => { + if(Array.isArray(subProps[key][optionProperty])) { + const optionArray = j.property( + 'init', + j.identifier(optionProperty), + j.arrayExpression([]) + ); + subProps[key][optionProperty].forEach( (n) => { + optionArray.value.elements.push(j.literal(n)); + }); + optionVal.value.properties.push(optionArray); + } else { + optionVal.value.properties.push( + j.property( + 'init', + j.identifier(optionProperty), + j.literal(key[optionProperty]) + ) + ); + } + }); + moduleProp.value.elements[seen].properties.push(optionVal); + } + if(key === 'use') { + let UseVal = j.property('init', j.identifier(key), j.arrayExpression([])); + + Object.keys(subProps[key]).forEach( (optionProperty) => { + if(typeof(subProps[key][optionProperty]) === 'string') { + UseVal.value.elements.push(j.literal(subProps[key][optionProperty])); + } else { + let loaderProperty = j.objectExpression([]); + + Object.keys(subProps[key][optionProperty]).forEach( subOptionProp => { + if(typeof(subProps[key][optionProperty][subOptionProp]) === 'string') { + loaderProperty.properties.push( + j.property('init', + j.identifier(subOptionProp), + j.literal(subProps[key][optionProperty][subOptionProp]) + ) + ); + } else { + let subSubProps = j.objectExpression([]); + Object.keys(subProps[key][optionProperty][subOptionProp]).forEach( (underlyingOption) => { + subSubProps.properties.push( + j.property('init', + j.identifier(underlyingOption), + j.literal( + subProps[key][optionProperty][subOptionProp][underlyingOption] + ) + ) + ); + }); + loaderProperty.properties.push(j.property('init', j.identifier(subOptionProp), subSubProps)); + } + }); + UseVal.value.elements.push(loaderProperty); + } + }); + moduleProp.value.elements[seen].properties.push(UseVal); + } + if(key === 'oneOf') { + // TODO + } + if(key === 'rules') { + // TODO + } + if(key === 'resource') { + // TODO + } + if(key === 'include' || key === 'exclude') { + let InExcludeVal = j.property('init', j.identifier(key), j.arrayExpression([])); + Object.keys(subProps[key]).forEach( (subProperty) => { + InExcludeVal.value.elements.push(j.literal(subProps[key][subProperty])); + }); + moduleProp.value.elements[seen].properties.push(InExcludeVal); + } + } + } + }); + }); + } + } + }); + }); + } + } + if(!webpackProperties['module']) { + return ast; + } else if(webpackProperties['module'].length) { + throw new Error('Supplying output with only no options is not supported.'); + } else { + return ast.find(j.ObjectExpression).filter(p => createModuleProperties(p)); + } +}; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 53b7c26d95d..9110b41d2dd 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -115,6 +115,75 @@ module.exports = class WebpackGenerator extends Generator { let SharedCache = {} this.configuration.webpackOptions.cache = SharedCache this.configuration.webpackOptions.profile = true + this.configuration.webpackOptions.module = { + noParse: pureRegExp('/jquery|lodash/'), + rules: [ + // rules for modules (configure loaders, parser options, etc.) + + { + test: pureRegExp("'/\\.jsx?$/'"), + include: [ + "../app" + ], + exclude: [ + "../app/demo-files" + ], + // these are matching conditions, each accepting a regular expression or string + // test and include have the same behavior, both must be matched + // exclude must not be matched (takes preferrence over test and include) + // Best practices: + // - Use RegExp only in test and for filename matching + // - Use arrays of absolute paths in include and exclude + // - Try to avoid exclude and prefer include + + // conditions for the issuer (the origin of the import) + + enforce: "pre", + // flags to apply these rules, even if they are overridden (advanced option) + + loader: "babel-loader", + // the loader which should be applied, it'll be resolved relative to the context + // -loader suffix is no longer optional in webpack2 for clarity reasons + // see webpack 1 upgrade guide + + options: { + presets: ["es2015"] + }, + // options for the loader + }, + + { + test: pureRegExp("'\\.html$'"), + + use: [ + // apply multiple loaders and options + "htmllint-loader", + { + loader: "html-loader", + options: { + hello: 'world' + } + } + ] + }, + + { oneOf: [] }, + // only use one of these nested rules + + { rules: [ ] }, + // use all of these nested rules (combine with conditions to be useful) + + { resource: { and: [ ] } }, + // matches only if all conditions are matched + + { resource: { or: [ ] } }, + { resource: [ ] }, + // matches if any condition is matched (default for arrays) + + { resource: { not: 'heo' } } + // matches if the condition is not matched + ], + } */ }); } From bf6a27ac4f4f5b6573ebf4bf97875bc61adaae8f Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 11 Apr 2017 13:16:35 +0200 Subject: [PATCH 030/101] feat: ast for plugins --- lib/creator/transformations/index.js | 4 ++- .../transformations/plugins/plugins.js | 31 ++++++++++--------- lib/creator/utils/addonsUtils.js | 6 +++- lib/creator/yeoman/webpack-generator.js | 7 +++++ 4 files changed, 32 insertions(+), 16 deletions(-) diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 8cde92c971e..f9bff1642c4 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -22,6 +22,7 @@ const bailTransform = require('./other/bail'); const cacheTransform = require('./other/cache'); const profileTransform = require('./other/profile'); const moduleTransform = require('./module/module'); +const pluginsTransform = require('./plugins/plugins'); /* * @function runTransform @@ -49,7 +50,8 @@ const transformsObject = { bailTransform, cacheTransform, profileTransform, - moduleTransform + moduleTransform, + pluginsTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index 8336fed5eda..411d9ca11f4 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -1,17 +1,20 @@ -const utils = require('../../../transformations/utils'); -/* -safeTraverse, -createProperty, -findPluginsByName, -findPluginsRootNodes, -createOrUpdatePluginByName, -findVariableToPlugin, -isType, -createLiteral, -findObjWithOneOfKeys, -getRequire -*/ module.exports = function(j, ast, webpackProperties) { - return ast.find(j.ObjectExpression); + function createPluginsProperty(p) { + if(p.parent.value.type === 'AssignmentExpression') { + const pluginArray = j.property('init', j.identifier('plugins'), j.arrayExpression([])); + Object.keys(webpackProperties.plugins).forEach( (plugin) => { + if(webpackProperties.plugins[plugin].__paths) { + const pluginVal = webpackProperties.plugins[plugin].__paths[0].value.program.body[0]; + pluginArray.value.elements.push(pluginVal); + } + }); + return p.value.properties.push(pluginArray); + } + } + if(webpackProperties['plugins'] && Array.isArray(webpackProperties['plugins'])) { + return ast.find(j.ObjectExpression).filter(p => createPluginsProperty(p)); + } else { + return ast; + } }; diff --git a/lib/creator/utils/addonsUtils.js b/lib/creator/utils/addonsUtils.js index e4a603eab9c..4bbc8a8fa55 100644 --- a/lib/creator/utils/addonsUtils.js +++ b/lib/creator/utils/addonsUtils.js @@ -28,6 +28,9 @@ function externalRegExp(regexp) { function pureRegExp(regexp) { return jscodeshift(regexp) }; +function commonChunksPluginCreate(value) { + return jscodeshift("new webpack.optimize.CommonsChunkPlugin({name:" + "'" + value + "'" + ",filename:" + "'" + value + "-[hash].min.js'})") +} module.exports = { arrowFunction, @@ -35,5 +38,6 @@ module.exports = { regularFunction, assetFilterFunction, externalRegExp, - pureRegExp + pureRegExp, + commonChunksPluginCreate }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 9110b41d2dd..5645c5c4a88 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -6,6 +6,8 @@ const parseFunction = require('../utils/addonsUtils').regularFunction; const assetFilterFunction = require('../utils/addonsUtils').assetFilterFunction; const externalRegExp = require('../utils/addonsUtils').externalRegExp; const pureRegExp = require('../utils/addonsUtils').pureRegExp; +const commonChunksPluginCreate = require('../utils/addonsUtils').commonChunksPluginCreate; + module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { super(args, opts); @@ -184,6 +186,11 @@ module.exports = class WebpackGenerator extends Generator { // matches if the condition is not matched ], } + this.configuration.webpackOptions.plugins = [ + commonChunksPluginCreate('myChunk'), + commonChunksPluginCreate('vendor'), + commonChunksPluginCreate('fp') + ] */ }); } From 3f9d953efa0c461098e2609cd09af33a5399b645 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 11 Apr 2017 14:32:33 +0200 Subject: [PATCH 031/101] feat: art for paths --- .../transformations/context/context.js | 9 +++++++- .../transformations/externals/externals.js | 10 ++++++-- lib/creator/transformations/module/module.js | 7 +++++- lib/creator/transformations/output/output.js | 14 +++++++---- .../transformations/resolve/resolve.js | 7 +++++- lib/creator/utils/addonsUtils.js | 8 +++++-- lib/creator/yeoman/webpack-generator.js | 23 +++++++++++-------- 7 files changed, 57 insertions(+), 21 deletions(-) diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index ad736d23c5b..9eb54611f92 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,7 +1,14 @@ module.exports = function(j, ast, webpackProperties) { function createContextProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(j.property('init', j.identifier('context'), j.literal(webpackProperties['context']))); + if(webpackProperties['context'].__paths) { + let contextProp = webpackProperties['context'].__paths[0].value.program.body[0].expression; + return p.value.properties.push(j.property('init', j.identifier('context'), contextProp)); + } else { + return p.value.properties.push( + j.property('init', j.identifier('context'), j.literal(webpackProperties['context'])) + ); + } } } if(webpackProperties['context'] && webpackProperties['context'].length) { diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 234dcadfc92..589bdbdbe71 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -18,7 +18,13 @@ module.exports = function(j, ast, webpackProperties) { // if we got a type, we make it an array const externalArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); webpackProperties.externals[webpackProp].forEach( (n) => { - return externalArray.value.elements.push(j.literal(n)); + if(n.__paths) { + externalArray.value.elements.push( + n.__paths[0].value.program.body[0] + ); + } else { + return externalArray.value.elements.push(j.literal(n)); + } }); prop.value.properties.push(externalArray); } @@ -46,7 +52,7 @@ module.exports = function(j, ast, webpackProperties) { externalProp.value.properties.push(subExternalArray); } else { externalProp.value.properties.push( - j.createProperty('init', j.identifier(subProps), j.literal(webpackProperties.externals[webpackProp][subProps])) + j.property('init', j.identifier(subProps), j.literal(webpackProperties.externals[webpackProp][subProps])) ); } }); diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 278be10a32e..2a5c927c5a9 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -123,7 +123,12 @@ module.exports = function(j, ast, webpackProperties) { if(key === 'include' || key === 'exclude') { let InExcludeVal = j.property('init', j.identifier(key), j.arrayExpression([])); Object.keys(subProps[key]).forEach( (subProperty) => { - InExcludeVal.value.elements.push(j.literal(subProps[key][subProperty])); + if(subProps[key][subProperty].__paths) { + let pathVar = subProps[key][subProperty].__paths[0].value.program.body[0].expression; + InExcludeVal.value.elements.push(pathVar); + } else { + InExcludeVal.value.elements.push(j.literal(subProps[key][subProperty])); + } }); moduleProp.value.elements[seen].properties.push(InExcludeVal); } diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 3650cb5899e..7f3822dd81c 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -10,10 +10,16 @@ module.exports = function(j, ast, webpackProperties) { Object.keys(webpackProperties.output).forEach( (webpackProp) => { if(webpackOutputTypes.includes(webpackProp)) { if(webpackProperties.output[webpackProp].__paths) { - let RegExpDec = webpackProperties.output[webpackProp].__paths[0].value.program.body[0].expression; - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(RegExpDec.value)) - ); + let RegExpDec = webpackProperties.output[webpackProp].__paths[0].value.program.body[0]; + if(RegExpDec.expression.callee) { + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), RegExpDec.expression) + ); + } else { + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.literal(RegExpDec.expression.value)) + ); + } } else { prop.value.properties.push( j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.output[webpackProp])) diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index 85351f5c92b..e4dbc831fbb 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -15,7 +15,12 @@ module.exports = function(j, ast, webpackProperties) { // if we got a type, we make it an array const resolveArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); webpackProperties.resolve[webpackProp].forEach( (n) => { - return resolveArray.value.elements.push(j.literal(n)); + if(n.__paths) { + let pluginExp = n.__paths[0].value.program.body[0].expression; + return resolveArray.value.elements.push(pluginExp); + } else { + return resolveArray.value.elements.push(j.literal(n)); + } }); prop.value.properties.push(resolveArray); } diff --git a/lib/creator/utils/addonsUtils.js b/lib/creator/utils/addonsUtils.js index 4bbc8a8fa55..86c400414f1 100644 --- a/lib/creator/utils/addonsUtils.js +++ b/lib/creator/utils/addonsUtils.js @@ -6,7 +6,7 @@ function arrowFunction(value) { return jscodeshift("() => " + "'" + value + "'"); }; function regularFunction(value, funcName) { - return jscodeshift("function " + funcName + "() {\n return " + "'" + value + "'" + "\n}"); + return jscodeshift("function " + funcName + "() {\n return " + value + "\n}"); }; function dynamicPromise(arr) { if(Array.isArray(arr)) { @@ -31,6 +31,9 @@ function pureRegExp(regexp) { function commonChunksPluginCreate(value) { return jscodeshift("new webpack.optimize.CommonsChunkPlugin({name:" + "'" + value + "'" + ",filename:" + "'" + value + "-[hash].min.js'})") } +function createPathProperty(one,two,three) { + return jscodeshift(one + '(' + two + ", '" + three + "')") +} module.exports = { arrowFunction, @@ -39,5 +42,6 @@ module.exports = { assetFilterFunction, externalRegExp, pureRegExp, - commonChunksPluginCreate + commonChunksPluginCreate, + createPathProperty }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 5645c5c4a88..d8a612a675c 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -7,6 +7,7 @@ const assetFilterFunction = require('../utils/addonsUtils').assetFilterFunction; const externalRegExp = require('../utils/addonsUtils').externalRegExp; const pureRegExp = require('../utils/addonsUtils').pureRegExp; const commonChunksPluginCreate = require('../utils/addonsUtils').commonChunksPluginCreate; +const createPathProperty = require('../utils/addonsUtils').createPathProperty; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { @@ -37,7 +38,7 @@ module.exports = class WebpackGenerator extends Generator { }; this.configuration.webpackOptions.entry = answeri; this.configuration.webpackOptions.output.filename = 'hello'; - this.configuration.webpackOptions.output.path = 'dist/assets'; + this.configuration.webpackOptions.output.path = createPathProperty('path.resolve', '__dirname', answer.entry); this.configuration.webpackOptions.output.pathinfo = true; this.configuration.webpackOptions.output.publicPath = "https://newbie.com" this.configuration.webpackOptions.output.sourceMapFilename = "[name].map" @@ -47,7 +48,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.webpackOptions.output.umdNamedDefine = true; this.configuration.webpackOptions.output.strictModuleExceptionHandling = true; - this.configuration.webpackOptions.context = '/hello' + this.configuration.webpackOptions.context = createPathProperty('path.resolve', '__dirname', "app") this.configuration.webpackOptions.resolve.alias.hello = ':)' this.configuration.webpackOptions.resolve.aliasFields = ["browser"] @@ -65,7 +66,9 @@ module.exports = class WebpackGenerator extends Generator { mainFields: ["loader", "main"], moduleExtensions: ['-loader'] } - this.configuration.webpackOptions.resolve.plugins = []; + this.configuration.webpackOptions.resolve.plugins = [ + commonChunksPluginCreate('myChunk') + ]; this.configuration.webpackOptions.resolve.symlinks = true; this.configuration.webpackOptions.resolve.cachePredicate = parseFunction(true, 'cachePredicate') this.configuration.webpackOptions.devtool = 'eval' @@ -79,7 +82,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.webpackOptions.externals = { jquery: 'jQuery', - subtract: ['./math', 'subtract'], + subtract: [createPathProperty('path.join', '__dirname', answer.entry), 'subtract'], lodash : { commonjs: "lodash", amd: "lodash", @@ -87,11 +90,11 @@ module.exports = class WebpackGenerator extends Generator { } } - this.configuration.webpackOptions.externals = [ - externalRegExp('^.js$') - ] + //this.configuration.webpackOptions.externals = [ + // externalRegExp('^.js$') + // ] - this.configuration.webpackOptions.externals = /^(jquery|\$)$/i + // this.configuration.webpackOptions.externals = /^(jquery|\$)$/i this.configuration.webpackOptions.node = { console: false, global: true, @@ -125,10 +128,10 @@ module.exports = class WebpackGenerator extends Generator { { test: pureRegExp("'/\\.jsx?$/'"), include: [ - "../app" + createPathProperty('path.resolve', "'../'", 'app') ], exclude: [ - "../app/demo-files" + createPathProperty('path.resolve', "'../app'", 'demo-files') ], // these are matching conditions, each accepting a regular expression or string // test and include have the same behavior, both must be matched From 026ee746f94fa798054d9759dd2867502f2134d1 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 11 Apr 2017 15:53:30 +0200 Subject: [PATCH 032/101] feat: prettier, topScope and runtime flow Adds the runtime flow, with prettier as well as some fixes to transformations + a top scope transformation. --- lib/creator/transformations/index.js | 47 ++++++++++++++----- lib/creator/transformations/other/cache.js | 2 +- lib/creator/transformations/output/output.js | 2 +- lib/creator/transformations/topScope/index.js | 11 +++++ lib/creator/utils/addonsUtils.js | 10 +++- lib/creator/yeoman/webpack-generator.js | 18 ++++--- 6 files changed, 66 insertions(+), 24 deletions(-) create mode 100644 lib/creator/transformations/topScope/index.js diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index f9bff1642c4..4b4e511f45f 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -1,5 +1,6 @@ const fs = require('fs'); const chalk = require('chalk'); +const spawn = require('cross-spawn'); const validateSchema = require('../../utils/validateSchema.js'); const webpackOptionsSchema = require('../../utils/webpackOptionsSchema.json'); const WebpackOptionsValidationError = require('../../utils/WebpackOptionsValidationError'); @@ -24,6 +25,8 @@ const profileTransform = require('./other/profile'); const moduleTransform = require('./module/module'); const pluginsTransform = require('./plugins/plugins'); +const topScopeTransform = require('./topScope/index'); + /* * @function runTransform * @@ -61,23 +64,45 @@ module.exports = function runTransform(yeomanConfig) { let ast = j('module.exports = {}'); return pEachSeries(transformations, f => f(j, ast, yeomanConfig.webpackOptions)) .then(() => { + if(yeomanConfig.topScope) { + topScopeTransform(j, ast, yeomanConfig.topScope); + } const recastOptions = { quote: 'single' }; const outputPath = process.cwd() + '/webpack.config.js'; const source = ast.toSource(recastOptions); - fs.writeFileSync(outputPath, source, 'utf-8'); - }) - .catch(err => { + const runPrettier = () => { + const processPromise = (child) => { + return new Promise(function(resolve, reject) { //eslint-disable-line + child.addListener('error', reject); + child.addListener('exit', resolve); + }); + }; + const spawnPrettier = () => { + console.log('\n'); + return spawn('prettier', ['--single-quote', '--trailing-comma es5', '--write', outputPath], { stdio: 'inherit', customFds: [0, 1, 2] }); + }; + processPromise(spawnPrettier()).then( () => { + try { + const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, require(outputPath)); + if (webpackOptionsValidationErrors.length) { + const errorMsg = new WebpackOptionsValidationError(webpackOptionsValidationErrors); + throw errorMsg.message; + } else { + process.stdout.write('\n' + chalk.green('Congratulations! Your new webpack config file is created!') + '\n'); + process.exit(0); + } + } catch(err) { + console.log('\n'); + console.error(err); + process.exit(-1); + } + }); + }; + fs.writeFile(outputPath, source, 'utf8', runPrettier); + }).catch(err => { console.error(err); }); } - /* - const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, initialWebpackConfig); - if (webpackOptionsValidationErrors.length) { - throw new WebpackOptionsValidationError(webpackOptionsValidationErrors); - } else { - process.stdout.write('\n' + chalk.green('Congratulations! Your new webpack config file is created!') + '\n'); - } - */ }; diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index b14a22bde55..8a97f90bcde 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -3,7 +3,7 @@ module.exports = function(j, ast, webpackProperties) { if(p.parent.value.type === 'AssignmentExpression') { // TODO: let people add obj by reference. // webpackProperties['cache'] - return p.value.properties.push(j.property('init', j.identifier('cache'), j.literal('TODO'))); + return p.value.properties.push(j.property('init', j.identifier('cache'), j.literal(true))); } } if(typeof(webpackProperties['cache']) === 'boolean') { diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 7f3822dd81c..ed7c34be7ed 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -9,7 +9,7 @@ module.exports = function(j, ast, webpackProperties) { prop.value.properties = []; Object.keys(webpackProperties.output).forEach( (webpackProp) => { if(webpackOutputTypes.includes(webpackProp)) { - if(webpackProperties.output[webpackProp].__paths) { + if(webpackProperties.output[webpackProp] && webpackProperties.output[webpackProp].__paths) { let RegExpDec = webpackProperties.output[webpackProp].__paths[0].value.program.body[0]; if(RegExpDec.expression.callee) { prop.value.properties.push( diff --git a/lib/creator/transformations/topScope/index.js b/lib/creator/transformations/topScope/index.js new file mode 100644 index 00000000000..c531914e50f --- /dev/null +++ b/lib/creator/transformations/topScope/index.js @@ -0,0 +1,11 @@ +module.exports = function(j, ast, webpackProperties) { + function createTopScopeProperty(p) { + webpackProperties.forEach( (n) => { + if(n.__paths) { + const topScopeVar = n.__paths[0].value.program.body[0]; + p.value.body.splice(-1, 0, topScopeVar); + } + }); + } + return ast.find(j.Program).filter(p => createTopScopeProperty(p)); +}; diff --git a/lib/creator/utils/addonsUtils.js b/lib/creator/utils/addonsUtils.js index 86c400414f1..3923da83512 100644 --- a/lib/creator/utils/addonsUtils.js +++ b/lib/creator/utils/addonsUtils.js @@ -35,6 +35,12 @@ function createPathProperty(one,two,three) { return jscodeshift(one + '(' + two + ", '" + three + "')") } +function createRequire(val) { + return jscodeshift("const " + val + " = " + "require(" + "'" + val + "'" + ");") +} +function createObject(obj) { + return jscodeshift(obj) +} module.exports = { arrowFunction, dynamicPromise, @@ -43,5 +49,7 @@ module.exports = { externalRegExp, pureRegExp, commonChunksPluginCreate, - createPathProperty + createPathProperty, + createRequire, + createObject }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index d8a612a675c..70dccffa4cb 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -8,6 +8,8 @@ const externalRegExp = require('../utils/addonsUtils').externalRegExp; const pureRegExp = require('../utils/addonsUtils').pureRegExp; const commonChunksPluginCreate = require('../utils/addonsUtils').commonChunksPluginCreate; const createPathProperty = require('../utils/addonsUtils').createPathProperty; +const createRequire = require('../utils/addonsUtils').createRequire; +const createObject = require('../utils/addonsUtils').createObject; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { @@ -22,7 +24,8 @@ module.exports = class WebpackGenerator extends Generator { alias: {}, aliasFields: [] } - } + }, + topScope: [] }; } prompting() { @@ -59,13 +62,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.webpackOptions.resolve.mainFields = ["mod", 'ho', 'bo'] this.configuration.webpackOptions.resolve.mainFiles = ["index"] this.configuration.webpackOptions.resolve.modules = ["Heo"] - this.configuration.webpackOptions.resolve.unsafeCache = pureRegExp("'/src\\/utilities/'") - this.configuration.webpackOptions.resolve.resolveLoader = { - modules: ["node_modules"], - extensions: [".js", ".json"], - mainFields: ["loader", "main"], - moduleExtensions: ['-loader'] - } + this.configuration.webpackOptions.resolve.unsafeCache = true; this.configuration.webpackOptions.resolve.plugins = [ commonChunksPluginCreate('myChunk') ]; @@ -82,7 +79,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.webpackOptions.externals = { jquery: 'jQuery', - subtract: [createPathProperty('path.join', '__dirname', answer.entry), 'subtract'], + subtract: 'tracty', lodash : { commonjs: "lodash", amd: "lodash", @@ -194,7 +191,8 @@ module.exports = class WebpackGenerator extends Generator { commonChunksPluginCreate('vendor'), commonChunksPluginCreate('fp') ] - */ + this.configuration.topScope = [createRequire('path'), createRequire('webpack'), createObject('var myObj = 9;')] + */ }); } config() {} From beda4db79b668bdb6111c678804eb6624a3c288f Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 11 Apr 2017 17:12:01 +0200 Subject: [PATCH 033/101] feat: ast for cache --- lib/creator/transformations/other/cache.js | 7 ++++--- lib/creator/yeoman/webpack-generator.js | 7 +++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index 8a97f90bcde..3b0c0229382 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,9 +1,10 @@ module.exports = function(j, ast, webpackProperties) { function createCacheProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - // TODO: let people add obj by reference. - // webpackProperties['cache'] - return p.value.properties.push(j.property('init', j.identifier('cache'), j.literal(true))); + if(webpackProperties['cache'].__paths) { + const cacheProp = webpackProperties['cache'].__paths[0].value.program.body[0].expression; + return p.value.properties.push(j.property('init', j.identifier('cache'), cacheProp)); + } } } if(typeof(webpackProperties['cache']) === 'boolean') { diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 70dccffa4cb..1fcded0647e 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -114,8 +114,7 @@ module.exports = class WebpackGenerator extends Generator { kQuery: false } this.configuration.webpackOptions.bail = true; - let SharedCache = {} - this.configuration.webpackOptions.cache = SharedCache + this.configuration.webpackOptions.cache = pureRegExp('myCache') this.configuration.webpackOptions.profile = true this.configuration.webpackOptions.module = { noParse: pureRegExp('/jquery|lodash/'), @@ -191,8 +190,8 @@ module.exports = class WebpackGenerator extends Generator { commonChunksPluginCreate('vendor'), commonChunksPluginCreate('fp') ] - this.configuration.topScope = [createRequire('path'), createRequire('webpack'), createObject('var myObj = 9;')] - */ + this.configuration.topScope = [createRequire('path'), createRequire('webpack'), createObject('const myCache = {};')] + */ }); } config() {} From ea398124ecc89d9909b2e4d633f19a22d83aea8e Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 11 Apr 2017 17:42:23 +0200 Subject: [PATCH 034/101] feat: module regexp fix --- lib/creator/transformations/module/module.js | 30 ++++++++++++++------ lib/creator/utils/addonsUtils.js | 6 +++- lib/creator/yeoman/webpack-generator.js | 8 ++---- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 2a5c927c5a9..a53da8da909 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -23,18 +23,30 @@ module.exports = function(j, ast, webpackProperties) { prop.value.properties.filter(n => n.key.name === webpackProp).forEach( moduleProp => { for(let key in subProps) { if(webpackModuleTypes.includes(key)) { - if(subProps[key].__paths && key === 'test') { + if(key === 'test') { moduleProp.value.elements.push(j.objectExpression([])); seen += 1; - moduleProp.value.elements[seen].properties.push( - j.property( - 'init', - j.identifier(key), - j.literal( - subProps[key].__paths[0].value.program.body[0].expression.rawValue + if(subProps[key].__paths) { + moduleProp.value.elements[seen].properties.push( + j.property( + 'init', + j.identifier(key), + j.literal( + subProps[key].__paths[0].value.program.body[0].expression.value + ) ) - ) - ); + ); + } else { + moduleProp.value.elements[seen].properties.push( + j.property( + 'init', + j.identifier(key), + j.literal( + subProps[key] + ) + ) + ); + } } if(key === 'enforce') { moduleProp.value.elements[seen].properties.push( diff --git a/lib/creator/utils/addonsUtils.js b/lib/creator/utils/addonsUtils.js index 3923da83512..b9ee0f66e10 100644 --- a/lib/creator/utils/addonsUtils.js +++ b/lib/creator/utils/addonsUtils.js @@ -28,6 +28,9 @@ function externalRegExp(regexp) { function pureRegExp(regexp) { return jscodeshift(regexp) }; +function moduleRegExp(regexp) { + return jscodeshift(`\\${regexp}`) +} function commonChunksPluginCreate(value) { return jscodeshift("new webpack.optimize.CommonsChunkPlugin({name:" + "'" + value + "'" + ",filename:" + "'" + value + "-[hash].min.js'})") } @@ -51,5 +54,6 @@ module.exports = { commonChunksPluginCreate, createPathProperty, createRequire, - createObject + createObject, + moduleRegExp }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 1fcded0647e..c7dfebd4adb 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -10,6 +10,7 @@ const commonChunksPluginCreate = require('../utils/addonsUtils').commonChunksPlu const createPathProperty = require('../utils/addonsUtils').createPathProperty; const createRequire = require('../utils/addonsUtils').createRequire; const createObject = require('../utils/addonsUtils').createObject; +const moduleRegExp = require('../utils/addonsUtils').moduleRegExp; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { @@ -122,7 +123,7 @@ module.exports = class WebpackGenerator extends Generator { // rules for modules (configure loaders, parser options, etc.) { - test: pureRegExp("'/\\.jsx?$/'"), + test: pureRegExp("/\.jsx?$/"), include: [ createPathProperty('path.resolve', "'../'", 'app') ], @@ -154,7 +155,7 @@ module.exports = class WebpackGenerator extends Generator { }, { - test: pureRegExp("'\\.html$'"), + test: new RegExp("\\.html$"), use: [ // apply multiple loaders and options @@ -195,9 +196,6 @@ module.exports = class WebpackGenerator extends Generator { }); } config() {} - childDependencies() { - this.configuration.childDependencies = ['webpack-addons-preact']; - } inject() {} }; From 02c9b14df3c474907a32eed44c02d0d285cdac46 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 11 Apr 2017 23:33:11 +0200 Subject: [PATCH 035/101] feat: fix generator methods --- lib/creator/utils/addonsUtils.js | 59 ----- lib/creator/yeoman/webpack-generator.js | 313 ++++++++++-------------- package.json | 2 +- 3 files changed, 130 insertions(+), 244 deletions(-) delete mode 100644 lib/creator/utils/addonsUtils.js diff --git a/lib/creator/utils/addonsUtils.js b/lib/creator/utils/addonsUtils.js deleted file mode 100644 index b9ee0f66e10..00000000000 --- a/lib/creator/utils/addonsUtils.js +++ /dev/null @@ -1,59 +0,0 @@ -/* eslint-disable */ -const jscodeshift = require('jscodeshift'); - -// moving to webpack-addons later -function arrowFunction(value) { - return jscodeshift("() => " + "'" + value + "'"); -}; -function regularFunction(value, funcName) { - return jscodeshift("function " + funcName + "() {\n return " + value + "\n}"); -}; -function dynamicPromise(arr) { - if(Array.isArray(arr)) { - return jscodeshift("() => new Promise((resolve) => resolve([" + arr.map( (n) => { - return "'" + n + "'" - }) + "]))"); - } else { - return jscodeshift("() => new Promise((resolve) => resolve(" + "'" + arr + "'" + "))"); - } -}; -function assetFilterFunction(value) { - return jscodeshift("function assetFilter" + "(assetFilename) {\n return assetFilename.endsWith(" + "'" + "." + value + "'" + ");\n}"); -}; -function externalRegExp(regexp) { - return jscodeshift("\n function externalRegExp(context, request, callback) {\n if (" - + "/" + regexp + "/.test(request)){" + "\n" + " return callback(null, 'commonjs ' + request);\n}\n" - + "callback();\n}") -}; -function pureRegExp(regexp) { - return jscodeshift(regexp) -}; -function moduleRegExp(regexp) { - return jscodeshift(`\\${regexp}`) -} -function commonChunksPluginCreate(value) { - return jscodeshift("new webpack.optimize.CommonsChunkPlugin({name:" + "'" + value + "'" + ",filename:" + "'" + value + "-[hash].min.js'})") -} -function createPathProperty(one,two,three) { - return jscodeshift(one + '(' + two + ", '" + three + "')") -} - -function createRequire(val) { - return jscodeshift("const " + val + " = " + "require(" + "'" + val + "'" + ");") -} -function createObject(obj) { - return jscodeshift(obj) -} -module.exports = { - arrowFunction, - dynamicPromise, - regularFunction, - assetFilterFunction, - externalRegExp, - pureRegExp, - commonChunksPluginCreate, - createPathProperty, - createRequire, - createObject, - moduleRegExp -}; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index c7dfebd4adb..d6d5db98890 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -1,201 +1,146 @@ const Generator = require('yeoman-generator'); -const Input = require('webpack-addons').Input; -const parseArrow = require('../utils/addonsUtils').arrowFunction; -const parsePromise = require('../utils/addonsUtils').dynamicPromise; -const parseFunction = require('../utils/addonsUtils').regularFunction; -const assetFilterFunction = require('../utils/addonsUtils').assetFilterFunction; -const externalRegExp = require('../utils/addonsUtils').externalRegExp; -const pureRegExp = require('../utils/addonsUtils').pureRegExp; -const commonChunksPluginCreate = require('../utils/addonsUtils').commonChunksPluginCreate; -const createPathProperty = require('../utils/addonsUtils').createPathProperty; -const createRequire = require('../utils/addonsUtils').createRequire; -const createObject = require('../utils/addonsUtils').createObject; -const moduleRegExp = require('../utils/addonsUtils').moduleRegExp; +const assetFilterFunction = require('webpack-addons').assetFilterFunction; +const externalRegExpFunction = require('webpack-addons').externalRegExpFunction; +const parseValue = require('webpack-addons').parseValue; +const commonChunksPluginCreate = require('webpack-addons').commonChunksPluginCreate; +const createPathProperty = require('webpack-addons').createPathProperty; +const createRequire = require('webpack-addons').createRequire; +const regularFunction = require('webpack-addons').regularFunction; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { super(args, opts); this.configuration = { - webpackOptions: { - output: { - filename: null, - path: null - }, - resolve: { - alias: {}, - aliasFields: [] - } - }, + webpackOptions: {}, topScope: [] }; } prompting() { - return this.prompt([Input('entry', 'What is the name of the entry point in your application?')]) - .then( (answer) => { - /* - let answeri = parsePromise(answer.entry); - this.configuration.webpackOptions.entry = { - vendor: 'home', - js: 'yes', - ohye: 'no', - nana: answeri - }; - this.configuration.webpackOptions.entry = answeri; - this.configuration.webpackOptions.output.filename = 'hello'; - this.configuration.webpackOptions.output.path = createPathProperty('path.resolve', '__dirname', answer.entry); - this.configuration.webpackOptions.output.pathinfo = true; - this.configuration.webpackOptions.output.publicPath = "https://newbie.com" - this.configuration.webpackOptions.output.sourceMapFilename = "[name].map" - - this.configuration.webpackOptions.output.sourcePrefix = pureRegExp("'\t'") - - this.configuration.webpackOptions.output.umdNamedDefine = true; - this.configuration.webpackOptions.output.strictModuleExceptionHandling = true; - - this.configuration.webpackOptions.context = createPathProperty('path.resolve', '__dirname', "app") - - this.configuration.webpackOptions.resolve.alias.hello = ':)' - this.configuration.webpackOptions.resolve.aliasFields = ["browser"] - this.configuration.webpackOptions.resolve.descriptionFiles = ['a', 'b'] - this.configuration.webpackOptions.resolve.enforceExtension = false - this.configuration.webpackOptions.resolve.enforceModuleExtension = false - this.configuration.webpackOptions.resolve.extensions = ['hey', 'gi'] - this.configuration.webpackOptions.resolve.mainFields = ["mod", 'ho', 'bo'] - this.configuration.webpackOptions.resolve.mainFiles = ["index"] - this.configuration.webpackOptions.resolve.modules = ["Heo"] - this.configuration.webpackOptions.resolve.unsafeCache = true; - this.configuration.webpackOptions.resolve.plugins = [ - commonChunksPluginCreate('myChunk') - ]; - this.configuration.webpackOptions.resolve.symlinks = true; - this.configuration.webpackOptions.resolve.cachePredicate = parseFunction(true, 'cachePredicate') - this.configuration.webpackOptions.devtool = 'eval' - this.configuration.webpackOptions.target = 'async-node' - this.configuration.webpackOptions.watch = true; - this.configuration.webpackOptions.watchOptions = { - aggregateTimeout: 300, - poll: 1000, - ignored: '/node_modules/' - } - - this.configuration.webpackOptions.externals = { - jquery: 'jQuery', - subtract: 'tracty', - lodash : { - commonjs: "lodash", - amd: "lodash", - root: "_" // indicates global variable - } - } - - //this.configuration.webpackOptions.externals = [ - // externalRegExp('^.js$') - // ] - - // this.configuration.webpackOptions.externals = /^(jquery|\$)$/i - this.configuration.webpackOptions.node = { - console: false, - global: true, - process: true, - Buffer: true, - __filename: "mock", - __dirname: "mock", - setImmediate: true + this.configuration.webpackOptions.entry = { + vendor: 'home', + js: 'yes', + ohye: 'no' + }; + this.configuration.webpackOptions.output = {}; + this.configuration.webpackOptions.output.filename = 'hello'; + this.configuration.webpackOptions.output.path = createPathProperty('path.resolve', '__dirname', 'something'); + this.configuration.webpackOptions.output.pathinfo = true; + this.configuration.webpackOptions.output.publicPath = 'https://newbie.com'; + this.configuration.webpackOptions.output.sourceMapFilename = '[name].map'; + /* eslint-disable */ + this.configuration.webpackOptions.output.sourcePrefix = parseValue("'\t'") + /* esline-enable */ + this.configuration.webpackOptions.output.umdNamedDefine = true; + this.configuration.webpackOptions.output.strictModuleExceptionHandling = true; + this.configuration.webpackOptions.context = createPathProperty('path.resolve', '__dirname', 'app') + this.configuration.webpackOptions.resolve = {}; + this.configuration.webpackOptions.resolve.alias = {}; + this.configuration.webpackOptions.resolve.alias.hello = ':)' + this.configuration.webpackOptions.resolve.aliasFields = ['browser'] + this.configuration.webpackOptions.resolve.descriptionFiles = ['a', 'b'] + this.configuration.webpackOptions.resolve.enforceExtension = false + this.configuration.webpackOptions.resolve.enforceModuleExtension = false + this.configuration.webpackOptions.resolve.extensions = ['hey', 'gi'] + this.configuration.webpackOptions.resolve.mainFields = ['mod', 'ho', 'bo'] + this.configuration.webpackOptions.resolve.mainFiles = ['index'] + this.configuration.webpackOptions.resolve.modules = ['Heo'] + this.configuration.webpackOptions.resolve.unsafeCache = true; + this.configuration.webpackOptions.resolve.plugins = [ + commonChunksPluginCreate('myChunk') + ]; + this.configuration.webpackOptions.resolve.symlinks = true; + this.configuration.webpackOptions.resolve.cachePredicate = regularFunction(true, 'cachePredicate') + this.configuration.webpackOptions.devtool = 'eval' + this.configuration.webpackOptions.target = 'async-node' + this.configuration.webpackOptions.watch = true; + this.configuration.webpackOptions.watchOptions = { + aggregateTimeout: 300, + poll: 1000, + ignored: '/node_modules/' + } + this.configuration.webpackOptions.externals = { + jquery: 'jQuery', + subtract: 'tracty', + lodash : { + commonjs: 'lodash', + amd: 'lodash', + root: '_' // indicates global variable } - this.configuration.webpackOptions.performance = { - hints: "warning", + } + this.configuration.webpackOptions.externals = [ + externalRegExpFunction('^.js$') + ] + this.configuration.webpackOptions.externals = /^(jquery|\$)$/i + this.configuration.webpackOptions.node = { + console: false, + global: true, + process: true, + Buffer: true, + __filename: 'mock', + __dirname: 'mock', + setImmediate: true + } + this.configuration.webpackOptions.performance = { + hints: 'warning', maxEntrypointSize: 400000, maxAssetSize: 100000, - assetFilter: assetFilterFunction('js') - } - this.configuration.webpackOptions.stats = 'errors-only' - this.configuration.webpackOptions.amd = { - jQuery: true, - kQuery: false - } - this.configuration.webpackOptions.bail = true; - this.configuration.webpackOptions.cache = pureRegExp('myCache') - this.configuration.webpackOptions.profile = true - this.configuration.webpackOptions.module = { - noParse: pureRegExp('/jquery|lodash/'), - rules: [ - // rules for modules (configure loaders, parser options, etc.) - - { - test: pureRegExp("/\.jsx?$/"), - include: [ - createPathProperty('path.resolve', "'../'", 'app') - ], - exclude: [ - createPathProperty('path.resolve', "'../app'", 'demo-files') - ], - // these are matching conditions, each accepting a regular expression or string - // test and include have the same behavior, both must be matched - // exclude must not be matched (takes preferrence over test and include) - // Best practices: - // - Use RegExp only in test and for filename matching - // - Use arrays of absolute paths in include and exclude - // - Try to avoid exclude and prefer include - - // conditions for the issuer (the origin of the import) - - enforce: "pre", - // flags to apply these rules, even if they are overridden (advanced option) - - loader: "babel-loader", - // the loader which should be applied, it'll be resolved relative to the context - // -loader suffix is no longer optional in webpack2 for clarity reasons - // see webpack 1 upgrade guide - - options: { - presets: ["es2015"] - }, - // options for the loader - }, - - { - test: new RegExp("\\.html$"), - - use: [ - // apply multiple loaders and options - "htmllint-loader", - { - loader: "html-loader", - options: { - hello: 'world' - } - } - ] - }, - - { oneOf: [] }, - // only use one of these nested rules - - { rules: [ ] }, - // use all of these nested rules (combine with conditions to be useful) - - { resource: { and: [ ] } }, - // matches only if all conditions are matched - - { resource: { or: [ ] } }, - { resource: [ ] }, - // matches if any condition is matched (default for arrays) - - { resource: { not: 'heo' } } - // matches if the condition is not matched - ], - } - this.configuration.webpackOptions.plugins = [ - commonChunksPluginCreate('myChunk'), - commonChunksPluginCreate('vendor'), - commonChunksPluginCreate('fp') - ] - this.configuration.topScope = [createRequire('path'), createRequire('webpack'), createObject('const myCache = {};')] - */ - }); + } + this.configuration.webpackOptions.stats = 'errors-only' + this.configuration.webpackOptions.amd = { + jQuery: true, + kQuery: false + } + this.configuration.webpackOptions.bail = true; + this.configuration.webpackOptions.cache = parseValue('myCache') + this.configuration.webpackOptions.profile = true + this.configuration.webpackOptions.module = { + noParse: new RegExp('/jquery|lodash/'), + rules: [ + { + test: new RegExp('/\.jsx?$/'), + include: [ + /* eslint-disable */ + createPathProperty('path.resolve', "'../'", 'app') + /* eslint-enable */ + ], + exclude: [ + /* eslint-disable */ + createPathProperty('path.resolve', "'../app'", 'demo-files') + /* eslint-enable */ + ], + enforce: 'pre', + loader: 'babel-loader', + options: { + presets: ['es2015'] + }, + }, + { + test: new RegExp('\\.html$'), + use: [ + 'htmllint-loader', + { + loader: 'html-loader', + options: { + hello: 'world' + } + } + ] + }, + { oneOf: [] }, + { rules: [ ] }, + { resource: { and: [ ] } }, + { resource: { or: [ ] } }, + { resource: [ ] }, + { resource: { not: 'heo' } } + ], + } + this.configuration.webpackOptions.plugins = [ + commonChunksPluginCreate('myChunk'), + commonChunksPluginCreate('vendor'), + commonChunksPluginCreate('fp') + ] + this.configuration.topScope = [createRequire('path'), createRequire('webpack'), parseValue('const myCache = {};')] } - config() {} - inject() {} }; diff --git a/package.json b/package.json index f9fc98705f8..8a55289beda 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "recast": "git://github.com/kalcifer/recast.git#bug/allowbreak", "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", - "webpack-addons": "0.0.20", + "webpack-addons": "^1.0.1", "webpack-addons-ylvis": "0.0.34", "yargs": "^6.5.0", "yeoman-environment": "^1.6.6", From 290e4f221d3166588dced817fbabb3ab5f60a3f9 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 11 Apr 2017 23:51:09 +0200 Subject: [PATCH 036/101] chore: bump add ons dep --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8a55289beda..2c332a9ac9e 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "recast": "git://github.com/kalcifer/recast.git#bug/allowbreak", "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", - "webpack-addons": "^1.0.1", + "webpack-addons": "^1.0.2", "webpack-addons-ylvis": "0.0.34", "yargs": "^6.5.0", "yeoman-environment": "^1.6.6", From aba04dd081017234873af64724b5d309bfedf77a Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Wed, 12 Apr 2017 01:29:16 +0200 Subject: [PATCH 037/101] feat: introduce scaffold for external runs --- lib/creator/index.js | 6 ++++-- lib/utils/resolve-packages.js | 19 ++++++++++++++----- package.json | 1 - 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/lib/creator/index.js b/lib/creator/index.js index 8f84dbe84fb..bd5ad6f7401 100644 --- a/lib/creator/index.js +++ b/lib/creator/index.js @@ -16,7 +16,7 @@ const runTransform = require('./transformations/index'); */ function creator(options) { - const env = yeoman.createEnv(null, null, new WebpackAdapter()); + let env = yeoman.createEnv('webpack', null, new WebpackAdapter()); const generatorName = options ? replaceGeneratorName(path.basename(options[0])) : 'webpack-default-generator'; if(options) { const WebpackGenerator = class extends Generator { @@ -33,7 +33,9 @@ function creator(options) { env.run(generatorName) .on('end', () => { - return runTransform(env.getArgument('configuration')); + //HACK / FIXME + env = env.options.env; + return runTransform(env.configuration); }); } diff --git a/lib/utils/resolve-packages.js b/lib/utils/resolve-packages.js index ab8b8561d55..7f4482a0452 100644 --- a/lib/utils/resolve-packages.js +++ b/lib/utils/resolve-packages.js @@ -1,7 +1,8 @@ -const spawn = require('cross-spawn'); -const creator = require('../creator/index').creator; const path = require('path'); +const fs = require('fs'); const chalk = require('chalk'); +const spawn = require('cross-spawn'); +const creator = require('../creator/index').creator; /* * @function processPromise @@ -29,8 +30,15 @@ function processPromise(child) { */ function spawnChild(pkg) { - return spawn('npm', ['install', '--save', pkg], { stdio: 'inherit', customFds: [0, 1, 2] }); - //return spawn('npm', ['install', '--save', pkg]); + // Different for windows, needs fix + if(fs.existsSync('/usr/local/lib/node_modules/' + pkg)) { + let removePath = '/usr/local/lib/node_modules/' + pkg; + // HACK / FIXME -> npm update right away doesn't install the updated pkg. + spawn('rm', ['-rf', removePath], { stdio: 'inherit', customFds: [0, 1, 2] }); + return spawn('npm', ['install', '-g', pkg], { stdio: 'inherit', customFds: [0, 1, 2] }); + } else { + return spawn('npm', ['install', '-g', pkg], { stdio: 'inherit', customFds: [0, 1, 2] }); + } } /* @@ -51,7 +59,8 @@ module.exports = function resolvePackages(pkg) { pkg.forEach( (addon) => { processPromise(spawnChild(addon)).then( () => { try { - packageLocations.push(path.join('..', '..', 'node_modules', addon)); + // Different for windows, needs fix + packageLocations.push(path.join('/usr', 'local', 'lib', 'node_modules', addon)); } catch(err) { console.log('Package wasn\'t validated correctly..'); console.log('Submit an issue for', pkg, 'if this persists'); diff --git a/package.json b/package.json index 2c332a9ac9e..d9149b82654 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,6 @@ "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", "webpack-addons": "^1.0.2", - "webpack-addons-ylvis": "0.0.34", "yargs": "^6.5.0", "yeoman-environment": "^1.6.6", "yeoman-generator": "git://github.com/ev1stensberg/generator.git#Feature-getArgument" From 6c59cda025d23e4628a76c865f3d82e063249751 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Wed, 12 Apr 2017 22:43:18 +0200 Subject: [PATCH 038/101] feat: don't use jscodeshift to parse unknown values --- lib/creator/index.js | 10 ++-- .../transformations/context/context.js | 14 ++---- .../transformations/devtool/devtool.js | 5 +- lib/creator/transformations/entry/entry.js | 3 +- .../transformations/externals/externals.js | 28 +++-------- lib/creator/transformations/index.js | 17 +++---- lib/creator/transformations/module/module.js | 48 +++++++------------ lib/creator/transformations/node/node.js | 15 ++++-- lib/creator/transformations/other/amd.js | 15 ++++-- lib/creator/transformations/other/bail.js | 7 ++- lib/creator/transformations/other/cache.js | 10 ++-- lib/creator/transformations/other/profile.js | 5 +- lib/creator/transformations/output/output.js | 33 ++++++------- .../performance/performance.js | 23 +++++---- .../transformations/plugins/plugins.js | 8 ++-- .../transformations/resolve/resolve.js | 29 +++++------ lib/creator/transformations/stats/stats.js | 7 +-- lib/creator/transformations/target/target.js | 5 +- lib/creator/transformations/topScope/index.js | 8 ++-- lib/creator/transformations/watch/watch.js | 3 +- .../transformations/watch/watchOptions.js | 15 ++++-- lib/creator/yeoman/webpack-generator.js | 43 ++++++++--------- package.json | 2 +- 23 files changed, 174 insertions(+), 179 deletions(-) diff --git a/lib/creator/index.js b/lib/creator/index.js index bd5ad6f7401..cf8fdc5894d 100644 --- a/lib/creator/index.js +++ b/lib/creator/index.js @@ -33,9 +33,13 @@ function creator(options) { env.run(generatorName) .on('end', () => { - //HACK / FIXME - env = env.options.env; - return runTransform(env.configuration); + if(generatorName !== 'webpack-default-generator') { + //HACK / FIXME + env = env.options.env; + return runTransform(env.configuration); + } else { + return runTransform(env.getArgument('configuration')); + } }); } diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 9eb54611f92..410b9523d26 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,14 +1,10 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createContextProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - if(webpackProperties['context'].__paths) { - let contextProp = webpackProperties['context'].__paths[0].value.program.body[0].expression; - return p.value.properties.push(j.property('init', j.identifier('context'), contextProp)); - } else { - return p.value.properties.push( - j.property('init', j.identifier('context'), j.literal(webpackProperties['context'])) - ); - } + return p.value.properties.push( + j.property('init', j.identifier('context'), j.identifier(webpackProperties['context'])) + ); } } if(webpackProperties['context'] && webpackProperties['context'].length) { diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index 1e1aac99af2..e4ed357fdb7 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,7 +1,8 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createDevToolProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(j.property('init', j.identifier('devtool'), j.literal(webpackProperties['devtool']))); + return p.value.properties.push(j.property('init', j.identifier('devtool'), j.identifier(webpackProperties['devtool']))); } } if(webpackProperties['devtool'] && webpackProperties['devtool'].length) { diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index accf730e93c..ec00182907d 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,4 +1,5 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createEntryProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(j.property('init', j.identifier('entry'), j.literal('null'))); diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 589bdbdbe71..126466374da 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -1,13 +1,11 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createExternalProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { if(webpackProperties.externals instanceof RegExp) { return p.value.properties.push(j.property('init', j.identifier('externals'), j.literal(webpackProperties.externals))); } - else if(webpackProperties.externals.__paths) { - let RegExpDec = webpackProperties.externals.__paths[0].value.program.body[0].expression.rawValue; - return p.value.properties.push(j.property('init', j.identifier('externals'), j.literal(RegExpDec))); - } else { + else { p.value.properties.push(j.property('init', j.identifier('externals'), j.literal('null'))); } p.value.properties.filter(node => node.key.name === 'externals').forEach( (prop) => { @@ -18,24 +16,12 @@ module.exports = function(j, ast, webpackProperties) { // if we got a type, we make it an array const externalArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); webpackProperties.externals[webpackProp].forEach( (n) => { - if(n.__paths) { - externalArray.value.elements.push( - n.__paths[0].value.program.body[0] - ); - } else { - return externalArray.value.elements.push(j.literal(n)); - } + return externalArray.value.elements.push(j.identifier(n)); }); prop.value.properties.push(externalArray); } else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.externals[webpackProp]))); - } - else if(webpackProperties.externals[webpackProp].__paths) { - let funcDec = webpackProperties.externals[webpackProp].__paths[0].value.program.body[0]; - prop.value.type = 'ArrayExpression'; - prop.value.elements = []; - prop.value.elements.push(funcDec); + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.externals[webpackProp]))); } else { prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); @@ -47,12 +33,12 @@ module.exports = function(j, ast, webpackProperties) { if(Array.isArray(webpackProperties.externals[webpackProp][subProps])) { const subExternalArray = j.property('init', j.identifier(subProps), j.arrayExpression([])); webpackProperties.externals[webpackProp][subProps].forEach( (n) => { - return subExternalArray.value.elements.push(j.literal(n)); + return subExternalArray.value.elements.push(j.identifier(n)); }); externalProp.value.properties.push(subExternalArray); } else { externalProp.value.properties.push( - j.property('init', j.identifier(subProps), j.literal(webpackProperties.externals[webpackProp][subProps])) + j.property('init', j.identifier(subProps), j.identifier(webpackProperties.externals[webpackProp][subProps])) ); } }); diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 4b4e511f45f..eaad8639942 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -54,24 +54,21 @@ const transformsObject = { cacheTransform, profileTransform, moduleTransform, - pluginsTransform + pluginsTransform, + topScopeTransform }; module.exports = function runTransform(yeomanConfig) { const transformations = Object.keys(transformsObject).map(k => transformsObject[k]); - if (yeomanConfig.webpackOptions) { let ast = j('module.exports = {}'); - return pEachSeries(transformations, f => f(j, ast, yeomanConfig.webpackOptions)) + return pEachSeries(transformations, f => f(j, ast, yeomanConfig)) .then(() => { - if(yeomanConfig.topScope) { - topScopeTransform(j, ast, yeomanConfig.topScope); - } - const recastOptions = { - quote: 'single' - }; + const outputPath = process.cwd() + '/webpack.config.js'; - const source = ast.toSource(recastOptions); + const source = ast.toSource({ + quote: 'single' + }); const runPrettier = () => { const processPromise = (child) => { return new Promise(function(resolve, reject) { //eslint-disable-line diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index a53da8da909..cca35a6e0dc 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -1,6 +1,7 @@ const webpackModuleTypes = require('./module-types'); -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createModuleProperties(p) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(j.property('init', j.identifier('module'), j.literal('null'))); @@ -26,36 +27,24 @@ module.exports = function(j, ast, webpackProperties) { if(key === 'test') { moduleProp.value.elements.push(j.objectExpression([])); seen += 1; - if(subProps[key].__paths) { - moduleProp.value.elements[seen].properties.push( - j.property( - 'init', - j.identifier(key), - j.literal( - subProps[key].__paths[0].value.program.body[0].expression.value - ) - ) - ); - } else { - moduleProp.value.elements[seen].properties.push( - j.property( - 'init', - j.identifier(key), - j.literal( - subProps[key] - ) + moduleProp.value.elements[seen].properties.push( + j.property( + 'init', + j.identifier(key), + j.literal( + subProps[key] ) - ); - } + ) + ); } if(key === 'enforce') { moduleProp.value.elements[seen].properties.push( - j.property('init', j.identifier(key), j.literal(subProps[key])) + j.property('init', j.identifier(key), j.identifier(subProps[key])) ); } if(key === 'loader') { moduleProp.value.elements[seen].properties.push( - j.property('init', j.identifier(key), j.literal(subProps[key])) + j.property('init', j.identifier(key), j.identifier(subProps[key])) ); } if(key === 'options') { @@ -91,7 +80,7 @@ module.exports = function(j, ast, webpackProperties) { Object.keys(subProps[key]).forEach( (optionProperty) => { if(typeof(subProps[key][optionProperty]) === 'string') { - UseVal.value.elements.push(j.literal(subProps[key][optionProperty])); + UseVal.value.elements.push(j.identifier(subProps[key][optionProperty])); } else { let loaderProperty = j.objectExpression([]); @@ -100,7 +89,7 @@ module.exports = function(j, ast, webpackProperties) { loaderProperty.properties.push( j.property('init', j.identifier(subOptionProp), - j.literal(subProps[key][optionProperty][subOptionProp]) + j.identifier(subProps[key][optionProperty][subOptionProp]) ) ); } else { @@ -109,7 +98,7 @@ module.exports = function(j, ast, webpackProperties) { subSubProps.properties.push( j.property('init', j.identifier(underlyingOption), - j.literal( + j.identifier( subProps[key][optionProperty][subOptionProp][underlyingOption] ) ) @@ -135,12 +124,7 @@ module.exports = function(j, ast, webpackProperties) { if(key === 'include' || key === 'exclude') { let InExcludeVal = j.property('init', j.identifier(key), j.arrayExpression([])); Object.keys(subProps[key]).forEach( (subProperty) => { - if(subProps[key][subProperty].__paths) { - let pathVar = subProps[key][subProperty].__paths[0].value.program.body[0].expression; - InExcludeVal.value.elements.push(pathVar); - } else { - InExcludeVal.value.elements.push(j.literal(subProps[key][subProperty])); - } + InExcludeVal.value.elements.push(j.identifier(subProps[key][subProperty])); }); moduleProp.value.elements[seen].properties.push(InExcludeVal); } diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index 20da35ab0c1..f40261c7cf1 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -1,4 +1,5 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createNodeProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(j.property('init', j.identifier('node'), j.literal('null'))); @@ -6,9 +7,15 @@ module.exports = function(j, ast, webpackProperties) { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.node).forEach( (webpackProp) => { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.node[webpackProp])) - ); + if(typeof(webpackProperties.node[webpackProp]) === 'boolean') { + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.node[webpackProp])) + ); + } else { + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.node[webpackProp])) + ); + } }); }); } diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index 11aaa38b489..5dc90818c05 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -1,4 +1,5 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createAMDProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(j.property('init', j.identifier('amd'), j.literal('null'))); @@ -6,9 +7,15 @@ module.exports = function(j, ast, webpackProperties) { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.amd).forEach( (webpackProp) => { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.amd[webpackProp])) - ); + if(typeof(webpackProperties.amd[webpackProp]) === 'boolean') { + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.amd[webpackProp])) + ); + } else { + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.amd[webpackProp])) + ); + } }); }); } diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index a5db0c96263..f6144393e56 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,7 +1,10 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createBailProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('bail'), j.literal(webpackProperties['bail']))); + let bailVal = (typeof webpackProperties['bail'] === 'boolean') + ? j.literal(webpackProperties['bail']) : j.identifier(webpackProperties['bail']); + p.value.properties.push(j.property('init', j.identifier('bail'), bailVal)); } } if(typeof(webpackProperties['bail']) === 'boolean') { diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index 3b0c0229382..36749dc329a 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,9 +1,11 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createCacheProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - if(webpackProperties['cache'].__paths) { - const cacheProp = webpackProperties['cache'].__paths[0].value.program.body[0].expression; - return p.value.properties.push(j.property('init', j.identifier('cache'), cacheProp)); + if(webpackProperties['cache']) { + return p.value.properties.push( + j.property('init', j.identifier('cache'), j.identifier(webpackProperties['cache'])) + ); } } } diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index ef59bb3ac9c..994f1501d5a 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,7 +1,8 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createProfileProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('profile'), j.literal(webpackProperties['profile']))); + p.value.properties.push(j.property('init', j.identifier('profile'), j.identifier(webpackProperties['profile']))); } } if(typeof(webpackProperties['profile']) === 'boolean') { diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index ed7c34be7ed..8935c67a2fe 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -1,30 +1,31 @@ const webpackOutputTypes = require('./output-types'); -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createOutputProperties(p) { if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('output'), j.literal('null'))); + p.value.properties.push(j.property('init', j.identifier('output'), j.objectExpression([]))); p.value.properties.filter( node => node.key.name === 'output').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; Object.keys(webpackProperties.output).forEach( (webpackProp) => { if(webpackOutputTypes.includes(webpackProp)) { - if(webpackProperties.output[webpackProp] && webpackProperties.output[webpackProp].__paths) { - let RegExpDec = webpackProperties.output[webpackProp].__paths[0].value.program.body[0]; - if(RegExpDec.expression.callee) { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), RegExpDec.expression) - ); - } else { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(RegExpDec.expression.value)) - ); - } - } else { + if(typeof webpackProperties.output[webpackProp] === 'boolean') { prop.value.properties.push( j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.output[webpackProp])) ); } + else if(webpackProperties.output[webpackProp].__paths) { + let regExpProp = webpackProperties.output[webpackProp].__paths[0].value.program.body[0].expression; + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.literal(regExpProp.value)) + ); + } + else { + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.output[webpackProp])) + ); + } + } else { + return ast; } }); }); diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index d84bbc2e879..416c011f5e3 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -1,6 +1,7 @@ const performanceTypes = require('./performance-types'); -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createPerformanceProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(j.property('init', j.identifier('performance'), j.literal('null'))); @@ -12,14 +13,18 @@ module.exports = function(j, ast, webpackProperties) { if(Array.isArray(webpackProperties.performance[webpackProp])) { throw new Error('Unknown Property', webpackProp); } - else if(webpackProperties.performance[webpackProp].__paths) { - let funcDec = webpackProperties.performance[webpackProp].__paths[0].value.program.body[0]; - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); - prop.value.properties.filter(node => node.key.name === webpackProp).forEach( (funcProp) => { - funcProp.value = funcDec; - }); - } else { - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.performance[webpackProp]))); + else { + if(typeof(webpackProperties.performance[webpackProp]) == 'string') { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.identifier(webpackProperties.performance[webpackProp]) + ) + ); + } else { + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.performance[webpackProp]))); + } } } else { throw new Error('Unknown Property', webpackProp); diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index 411d9ca11f4..c2797a20973 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -1,12 +1,12 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createPluginsProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { const pluginArray = j.property('init', j.identifier('plugins'), j.arrayExpression([])); Object.keys(webpackProperties.plugins).forEach( (plugin) => { - if(webpackProperties.plugins[plugin].__paths) { - const pluginVal = webpackProperties.plugins[plugin].__paths[0].value.program.body[0]; - pluginArray.value.elements.push(pluginVal); + if(webpackProperties.plugins[plugin]) { + pluginArray.value.elements.push(webpackProperties.plugins[plugin]); } }); return p.value.properties.push(pluginArray); diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index e4dbc831fbb..c4067839454 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -1,6 +1,7 @@ const resolveTypes = require('./resolve-types'); -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createResolveProperties(p) { if(webpackProperties['resolve']) { if(p.parent.value.type === 'AssignmentExpression') { @@ -15,24 +16,13 @@ module.exports = function(j, ast, webpackProperties) { // if we got a type, we make it an array const resolveArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); webpackProperties.resolve[webpackProp].forEach( (n) => { - if(n.__paths) { - let pluginExp = n.__paths[0].value.program.body[0].expression; - return resolveArray.value.elements.push(pluginExp); - } else { - return resolveArray.value.elements.push(j.literal(n)); - } + return resolveArray.value.elements.push(j.identifier(n)); }); prop.value.properties.push(resolveArray); } else if(typeof(webpackProperties.resolve[webpackProp]) === 'boolean') { let boolExp = j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.resolve[webpackProp])); prop.value.properties.push(boolExp); - } else if(webpackProperties.resolve[webpackProp].__paths) { - let funcDec = webpackProperties.resolve[webpackProp].__paths[0].value.program.body[0]; - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); - prop.value.properties.filter(node => node.key.name === webpackProp).forEach( (funcProp) => { - funcProp.value = funcDec; - }); } else { prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); @@ -40,16 +30,23 @@ module.exports = function(j, ast, webpackProperties) { if(resolveProp.key.name === webpackProp) { resolveProp.value.type = 'ObjectExpression'; resolveProp.value.properties = []; + if(resolveProp.key.name === 'cachePredicate') { + let cachePredicateVal = (typeof webpackProperties.resolve[webpackProp] === 'string') ? + j.identifier(webpackProperties.resolve[webpackProp]) : + j.literal(webpackProperties.resolve[webpackProp]); + resolveProp.value = cachePredicateVal; + + } Object.keys(webpackProperties.resolve[webpackProp]).forEach( (aliasProps) => { if(Array.isArray(webpackProperties.resolve[webpackProp][aliasProps])) { const resolveLoaderArray = j.property('init', j.identifier(aliasProps), j.arrayExpression([])); webpackProperties.resolve[webpackProp][aliasProps].forEach( (n) => { - return resolveLoaderArray.value.elements.push(j.literal(n)); + return resolveLoaderArray.value.elements.push(j.identifier(n)); }); resolveProp.value.properties.push(resolveLoaderArray); - } else { + } else if(webpackProperties.resolve[webpackProp][aliasProps].length > 1) { resolveProp.value.properties.push( - j.property('init', j.identifier(aliasProps), j.literal(webpackProperties.resolve[webpackProp][aliasProps])) + j.property('init', j.identifier(aliasProps), j.identifier(webpackProperties.resolve[webpackProp][aliasProps])) ); } }); diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index e2cf090f335..634fa1e8fed 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -1,6 +1,7 @@ const statsTypes = require('./stats-types'); -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createStatsProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(j.property('init', j.identifier('stats'), j.literal('null'))); @@ -17,7 +18,7 @@ module.exports = function(j, ast, webpackProperties) { prop.value.properties.push(statsArray); } else { - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.stats[webpackProp]))); + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.stats[webpackProp]))); } } else { throw new Error('Unknown Property', webpackProp); @@ -32,7 +33,7 @@ module.exports = function(j, ast, webpackProperties) { else if(webpackProperties['stats'] && webpackProperties['stats'].length) { return ast.find(j.ObjectExpression).filter(p => { if(p.parent.value.type === 'AssignmentExpression') - return p.value.properties.push(j.property('init', j.identifier('stats'), j.literal(webpackProperties['stats']))); + return p.value.properties.push(j.property('init', j.identifier('stats'), j.identifier(webpackProperties['stats']))); }); } else { diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 596ea525041..312bbb6087d 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,7 +1,8 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createTargetProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(j.property('init', j.identifier('target'), j.literal(webpackProperties['target']))); + return p.value.properties.push(j.property('init', j.identifier('target'), j.identifier(webpackProperties['target']))); } } if(webpackProperties['target'] && webpackProperties['target'].length) { diff --git a/lib/creator/transformations/topScope/index.js b/lib/creator/transformations/topScope/index.js index c531914e50f..c1b3b931ffc 100644 --- a/lib/creator/transformations/topScope/index.js +++ b/lib/creator/transformations/topScope/index.js @@ -1,10 +1,8 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.topScope; function createTopScopeProperty(p) { webpackProperties.forEach( (n) => { - if(n.__paths) { - const topScopeVar = n.__paths[0].value.program.body[0]; - p.value.body.splice(-1, 0, topScopeVar); - } + p.value.body.splice(-1, 0, n); }); } return ast.find(j.Program).filter(p => createTopScopeProperty(p)); diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index ed868995912..563f57b67f8 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,4 +1,5 @@ -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createWatchProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { return p.value.properties.push(j.property('init', j.identifier('watch'), j.literal(webpackProperties['watch']))); diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index 741eb864051..094e7bd349f 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -1,6 +1,7 @@ const watchOptionTypes = require('./watchOptions-types'); -module.exports = function(j, ast, webpackProperties) { +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; function createWatchOptionsProperty(p) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(j.property('init', j.identifier('watchOptions'), j.literal('null'))); @@ -9,9 +10,15 @@ module.exports = function(j, ast, webpackProperties) { prop.value.properties = []; Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { if(watchOptionTypes.includes(watchOption)) { - prop.value.properties.push( - j.property('init', j.identifier(watchOption), j.literal(webpackProperties['watchOptions'][watchOption])) - ); + if(typeof(webpackProperties['watchOptions'][watchOption]) === 'number') { + prop.value.properties.push( + j.property('init', j.identifier(watchOption), j.literal(webpackProperties['watchOptions'][watchOption])) + ); + } else { + prop.value.properties.push( + j.property('init', j.identifier(watchOption), j.identifier(webpackProperties['watchOptions'][watchOption])) + ); + } } else { throw new Error('Unknown Property', watchOption); } diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index d6d5db98890..381bf8bb416 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -1,11 +1,8 @@ +/* eslint-disable quotes */ const Generator = require('yeoman-generator'); const assetFilterFunction = require('webpack-addons').assetFilterFunction; const externalRegExpFunction = require('webpack-addons').externalRegExpFunction; const parseValue = require('webpack-addons').parseValue; -const commonChunksPluginCreate = require('webpack-addons').commonChunksPluginCreate; -const createPathProperty = require('webpack-addons').createPathProperty; -const createRequire = require('webpack-addons').createRequire; -const regularFunction = require('webpack-addons').regularFunction; module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { @@ -22,34 +19,34 @@ module.exports = class WebpackGenerator extends Generator { ohye: 'no' }; this.configuration.webpackOptions.output = {}; - this.configuration.webpackOptions.output.filename = 'hello'; - this.configuration.webpackOptions.output.path = createPathProperty('path.resolve', '__dirname', 'something'); + this.configuration.webpackOptions.output.filename = "'hello'"; + this.configuration.webpackOptions.output.path = 'path.join(__dirname, "somepath")'; this.configuration.webpackOptions.output.pathinfo = true; - this.configuration.webpackOptions.output.publicPath = 'https://newbie.com'; - this.configuration.webpackOptions.output.sourceMapFilename = '[name].map'; + this.configuration.webpackOptions.output.publicPath = "'https://newbie.com'"; + this.configuration.webpackOptions.output.sourceMapFilename = "'[name].map'"; /* eslint-disable */ this.configuration.webpackOptions.output.sourcePrefix = parseValue("'\t'") /* esline-enable */ this.configuration.webpackOptions.output.umdNamedDefine = true; this.configuration.webpackOptions.output.strictModuleExceptionHandling = true; - this.configuration.webpackOptions.context = createPathProperty('path.resolve', '__dirname', 'app') + this.configuration.webpackOptions.context = 'path.resolve(__dirname, "app")' this.configuration.webpackOptions.resolve = {}; this.configuration.webpackOptions.resolve.alias = {}; this.configuration.webpackOptions.resolve.alias.hello = ':)' - this.configuration.webpackOptions.resolve.aliasFields = ['browser'] - this.configuration.webpackOptions.resolve.descriptionFiles = ['a', 'b'] + this.configuration.webpackOptions.resolve.aliasFields = ["'browser'"] + this.configuration.webpackOptions.resolve.descriptionFiles = ["'a'", "'b'"] this.configuration.webpackOptions.resolve.enforceExtension = false this.configuration.webpackOptions.resolve.enforceModuleExtension = false - this.configuration.webpackOptions.resolve.extensions = ['hey', 'gi'] - this.configuration.webpackOptions.resolve.mainFields = ['mod', 'ho', 'bo'] - this.configuration.webpackOptions.resolve.mainFiles = ['index'] - this.configuration.webpackOptions.resolve.modules = ['Heo'] + this.configuration.webpackOptions.resolve.extensions = ["'hey'", "'gi'"] + this.configuration.webpackOptions.resolve.mainFields = ["'mod'", "'ho'", "'bo'"] + this.configuration.webpackOptions.resolve.mainFiles = ["'index'"] + this.configuration.webpackOptions.resolve.modules = ["'Heo'"] this.configuration.webpackOptions.resolve.unsafeCache = true; this.configuration.webpackOptions.resolve.plugins = [ - commonChunksPluginCreate('myChunk') + "new webpack.optimize.CommonsChunkPlugin({name:" + "'" + 'vendor' + "'" + ",filename:" + "'" + 'vendor' + "-[hash].min.js'})" ]; this.configuration.webpackOptions.resolve.symlinks = true; - this.configuration.webpackOptions.resolve.cachePredicate = regularFunction(true, 'cachePredicate') + this.configuration.webpackOptions.resolve.cachePredicate = "function()" + "{\n return " + "true" + "\n}"; this.configuration.webpackOptions.devtool = 'eval' this.configuration.webpackOptions.target = 'async-node' this.configuration.webpackOptions.watch = true; @@ -81,7 +78,7 @@ module.exports = class WebpackGenerator extends Generator { setImmediate: true } this.configuration.webpackOptions.performance = { - hints: 'warning', + hints: "'warning'", maxEntrypointSize: 400000, maxAssetSize: 100000, assetFilter: assetFilterFunction('js') @@ -101,12 +98,12 @@ module.exports = class WebpackGenerator extends Generator { test: new RegExp('/\.jsx?$/'), include: [ /* eslint-disable */ - createPathProperty('path.resolve', "'../'", 'app') + 'path.resolve(__dirname, "app")' /* eslint-enable */ ], exclude: [ /* eslint-disable */ - createPathProperty('path.resolve', "'../app'", 'demo-files') + 'path.resolve(__dirname, ".." , "app", "demo-files")' /* eslint-enable */ ], enforce: 'pre', @@ -136,11 +133,9 @@ module.exports = class WebpackGenerator extends Generator { ], } this.configuration.webpackOptions.plugins = [ - commonChunksPluginCreate('myChunk'), - commonChunksPluginCreate('vendor'), - commonChunksPluginCreate('fp') + "new webpack.optimize.CommonsChunkPlugin({name:" + "'" + 'vendor' + "'" + ",filename:" + "'" + 'vendor' + "-[hash].min.js'})" ] - this.configuration.topScope = [createRequire('path'), createRequire('webpack'), parseValue('const myCache = {};')] + this.configuration.topScope = ['const path = require("path");', 'const webpack = require("webpack");', 'const myCache = {};'] } }; diff --git a/package.json b/package.json index d9149b82654..ffa07e19d9f 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "recast": "git://github.com/kalcifer/recast.git#bug/allowbreak", "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", - "webpack-addons": "^1.0.2", + "webpack-addons": "^1.0.5", "yargs": "^6.5.0", "yeoman-environment": "^1.6.6", "yeoman-generator": "git://github.com/ev1stensberg/generator.git#Feature-getArgument" From d58695253f08de2c270d0037281ed5d51b1220a3 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Wed, 12 Apr 2017 23:08:13 +0200 Subject: [PATCH 039/101] feat: allow name conventions --- lib/creator/transformations/index.js | 68 +++++++++++++++------------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index eaad8639942..c9f8281c47f 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -64,40 +64,44 @@ module.exports = function runTransform(yeomanConfig) { let ast = j('module.exports = {}'); return pEachSeries(transformations, f => f(j, ast, yeomanConfig)) .then(() => { - - const outputPath = process.cwd() + '/webpack.config.js'; - const source = ast.toSource({ - quote: 'single' - }); - const runPrettier = () => { - const processPromise = (child) => { - return new Promise(function(resolve, reject) { //eslint-disable-line - child.addListener('error', reject); - child.addListener('exit', resolve); + yeomanConfig.configFiles.forEach( (name) => { + const outputPath = process.cwd() + '/webpack.' + name + '.js'; + const source = ast.toSource({ + quote: 'single' + }); + const runPrettier = () => { + const processPromise = (child) => { + return new Promise(function(resolve, reject) { //eslint-disable-line + child.addListener('error', reject); + child.addListener('exit', resolve); + }); + }; + const spawnPrettier = () => { + console.log('\n'); + return spawn( + 'prettier', ['--single-quote', '--trailing-comma es5', '--write', outputPath], + { stdio: 'inherit', customFds: [0, 1, 2] } + ); + }; + processPromise(spawnPrettier()).then( () => { + try { + const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, require(outputPath)); + if (webpackOptionsValidationErrors.length) { + const errorMsg = new WebpackOptionsValidationError(webpackOptionsValidationErrors); + throw errorMsg.message; + } else { + process.stdout.write('\n' + chalk.green('Congratulations! Your new webpack config file is created!') + '\n'); + process.exit(0); + } + } catch(err) { + console.log('\n'); + console.error(err); + process.exit(-1); + } }); }; - const spawnPrettier = () => { - console.log('\n'); - return spawn('prettier', ['--single-quote', '--trailing-comma es5', '--write', outputPath], { stdio: 'inherit', customFds: [0, 1, 2] }); - }; - processPromise(spawnPrettier()).then( () => { - try { - const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, require(outputPath)); - if (webpackOptionsValidationErrors.length) { - const errorMsg = new WebpackOptionsValidationError(webpackOptionsValidationErrors); - throw errorMsg.message; - } else { - process.stdout.write('\n' + chalk.green('Congratulations! Your new webpack config file is created!') + '\n'); - process.exit(0); - } - } catch(err) { - console.log('\n'); - console.error(err); - process.exit(-1); - } - }); - }; - fs.writeFile(outputPath, source, 'utf8', runPrettier); + fs.writeFile(outputPath, source, 'utf8', runPrettier); + }); }).catch(err => { console.error(err); }); From 559af8c96f9b4b5a54b581a095c6ca7023203b1f Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Wed, 12 Apr 2017 23:40:08 +0200 Subject: [PATCH 040/101] feat: allow multiple config creations --- lib/creator/transformations/index.js | 88 ++++++++++++++-------------- 1 file changed, 45 insertions(+), 43 deletions(-) diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index c9f8281c47f..9c3dee5e89b 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -60,50 +60,52 @@ const transformsObject = { module.exports = function runTransform(yeomanConfig) { const transformations = Object.keys(transformsObject).map(k => transformsObject[k]); - if (yeomanConfig.webpackOptions) { + Object.keys(yeomanConfig).forEach( (scaffoldPiece) => { + const config = yeomanConfig[scaffoldPiece]; let ast = j('module.exports = {}'); - return pEachSeries(transformations, f => f(j, ast, yeomanConfig)) - .then(() => { - yeomanConfig.configFiles.forEach( (name) => { - const outputPath = process.cwd() + '/webpack.' + name + '.js'; - const source = ast.toSource({ - quote: 'single' + return pEachSeries(transformations, f => f(j, ast, config)) + .then(() => { + + const outputPath = process.cwd() + '/webpack.' + (config.configName ? config.configName : 'config') + '.js'; + const source = ast.toSource({ + quote: 'single' + }); + const runPrettier = () => { + const processPromise = (child) => { + return new Promise(function(resolve, reject) { //eslint-disable-line + child.addListener('error', reject); + child.addListener('exit', resolve); }); - const runPrettier = () => { - const processPromise = (child) => { - return new Promise(function(resolve, reject) { //eslint-disable-line - child.addListener('error', reject); - child.addListener('exit', resolve); - }); - }; - const spawnPrettier = () => { - console.log('\n'); - return spawn( - 'prettier', ['--single-quote', '--trailing-comma es5', '--write', outputPath], - { stdio: 'inherit', customFds: [0, 1, 2] } - ); - }; - processPromise(spawnPrettier()).then( () => { - try { - const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, require(outputPath)); - if (webpackOptionsValidationErrors.length) { - const errorMsg = new WebpackOptionsValidationError(webpackOptionsValidationErrors); - throw errorMsg.message; - } else { - process.stdout.write('\n' + chalk.green('Congratulations! Your new webpack config file is created!') + '\n'); - process.exit(0); - } - } catch(err) { - console.log('\n'); - console.error(err); - process.exit(-1); - } - }); - }; - fs.writeFile(outputPath, source, 'utf8', runPrettier); + }; + const spawnPrettier = () => { + console.log('\n'); + return spawn( + 'prettier', ['--single-quote', '--trailing-comma es5', '--write', outputPath], + { stdio: 'inherit', customFds: [0, 1, 2] } + ); + }; + processPromise(spawnPrettier()).then( () => { + try { + const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, require(outputPath)); + if (webpackOptionsValidationErrors.length) { + const errorMsg = new WebpackOptionsValidationError(webpackOptionsValidationErrors); + throw errorMsg.message; + } else { + process.stdout.write('\n' + chalk.green( + 'Congratulations! Your new webpack config file is created!' + ) + '\n'); + process.exit(0); + } + } catch(err) { + console.log('\n'); + console.error(err); + process.exit(-1); + } }); - }).catch(err => { - console.error(err); - }); - } + }; + fs.writeFile(outputPath, source, 'utf8', runPrettier); + }).catch(err => { + console.error(err); + }); + }); }; From 89e0376acbaab34f8f07d0f2c9272b8eebc07932 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Thu, 13 Apr 2017 17:42:46 +0200 Subject: [PATCH 041/101] feat: allow using inject for resolve and module --- lib/creator/transformations/entry/entry.js | 27 +++----- lib/creator/transformations/module/module.js | 61 ++++++++++++------- .../transformations/resolve/resolve.js | 12 +++- 3 files changed, 58 insertions(+), 42 deletions(-) diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index ec00182907d..f245e3edc5b 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -4,29 +4,20 @@ module.exports = function(j, ast, yeomanConfig) { if(p.parent.value.type === 'AssignmentExpression') { p.value.properties.push(j.property('init', j.identifier('entry'), j.literal('null'))); p.value.properties.filter(node => node.key.name === 'entry').forEach( (prop) => { - if((webpackProperties['entry'] && webpackProperties['entry'].length) && !webpackProperties['entry'].__paths) { + if((webpackProperties['entry'] && webpackProperties['entry'].length)) { prop.value.value = webpackProperties['entry']; } - else if(webpackProperties['entry'].__paths) { - let funcDec = webpackProperties.entry.__paths[0].value.program.body[0]; - prop.value = funcDec; - } else { + else { prop.value.type = 'ObjectExpression'; prop.value.properties = []; Object.keys(webpackProperties.entry).forEach( (webpackProps) => { - if(webpackProperties.entry[webpackProps].__paths) { - let funcDec = webpackProperties.entry[webpackProps].__paths[0].value.program.body[0]; - prop.value.properties.push( - j.property('init', j.identifier(webpackProps), j.literal('null')) - ); - prop.value.properties.filter(node => node.key.name === webpackProps).forEach( (funcProp) => { - funcProp.value = funcDec; - }); - } else { - prop.value.properties.push( - j.property('init', j.identifier(webpackProps), j.literal(webpackProperties.entry[webpackProps])) - ); - } + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProps), + j.identifier(webpackProperties.entry[webpackProps]) + ) + ); }); } }); diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index cca35a6e0dc..f75040cf525 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -23,6 +23,10 @@ module.exports = function(j, ast, yeomanConfig) { webpackProperties.module[webpackProp].forEach( (subProps) => { prop.value.properties.filter(n => n.key.name === webpackProp).forEach( moduleProp => { for(let key in subProps) { + if(key.indexOf('inject') >= 0) { + moduleProp.value.elements.push(subProps[key]); + seen += 1; + } if(webpackModuleTypes.includes(key)) { if(key === 'test') { moduleProp.value.elements.push(j.objectExpression([])); @@ -49,30 +53,45 @@ module.exports = function(j, ast, yeomanConfig) { } if(key === 'options') { let optionVal = j.property('init', j.identifier(key), j.identifier('presets')); - optionVal.value.type = 'ObjectExpression'; - optionVal.value.properties = []; - Object.keys(subProps[key]).forEach( (optionProperty) => { - if(Array.isArray(subProps[key][optionProperty])) { - const optionArray = j.property( - 'init', - j.identifier(optionProperty), - j.arrayExpression([]) - ); - subProps[key][optionProperty].forEach( (n) => { - optionArray.value.elements.push(j.literal(n)); - }); - optionVal.value.properties.push(optionArray); - } else { - optionVal.value.properties.push( - j.property( + if(typeof(subProps[key]) === 'string') { + optionVal.value = j.identifier(subProps[key]); + } else { + optionVal.value.type = 'ObjectExpression'; + optionVal.value.properties = []; + Object.keys(subProps[key]).forEach( (optionProperty) => { + + if(Array.isArray(subProps[key][optionProperty])) { + const optionArray = j.property( 'init', j.identifier(optionProperty), - j.literal(key[optionProperty]) - ) - ); - } - }); + j.arrayExpression([]) + ); + subProps[key][optionProperty].forEach( (n) => { + optionArray.value.elements.push(j.literal(n)); + }); + optionVal.value.properties.push(optionArray); + } else { + if(typeof(subProps[key][optionProperty]) === 'string') { + optionVal.value.properties.push( + j.property( + 'init', + j.identifier(optionProperty), + j.identifier(subProps[key][optionProperty]) + ) + ); + } else { + optionVal.value.properties.push( + j.property( + 'init', + j.identifier(optionProperty), + j.literal(subProps[key][optionProperty]) + ) + ); + } + } + }); + } moduleProp.value.elements[seen].properties.push(optionVal); } if(key === 'use') { diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index c4067839454..ed86068f9f0 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -45,9 +45,15 @@ module.exports = function(j, ast, yeomanConfig) { }); resolveProp.value.properties.push(resolveLoaderArray); } else if(webpackProperties.resolve[webpackProp][aliasProps].length > 1) { - resolveProp.value.properties.push( - j.property('init', j.identifier(aliasProps), j.identifier(webpackProperties.resolve[webpackProp][aliasProps])) - ); + if(aliasProps.indexOf('inject') >= 0) { + resolveProp.value.properties.push(j.identifier( + webpackProperties.resolve[webpackProp][aliasProps] + )); + } else { + resolveProp.value.properties.push( + j.property('init', j.identifier(aliasProps), j.identifier(webpackProperties.resolve[webpackProp][aliasProps])) + ); + } } }); } From ba01b69b0e9d84d41960e97fe5496557e591d03f Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Thu, 13 Apr 2017 19:37:39 +0200 Subject: [PATCH 042/101] feat: allow merge in scaffold --- lib/creator/transformations/index.js | 5 +-- lib/creator/transformations/module/module.js | 2 ++ lib/creator/transformations/other/merge.js | 33 ++++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 lib/creator/transformations/other/merge.js diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 9c3dee5e89b..2ba56d42bcd 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -22,9 +22,9 @@ const amdTransform = require('./other/amd'); const bailTransform = require('./other/bail'); const cacheTransform = require('./other/cache'); const profileTransform = require('./other/profile'); +const mergeTransform = require('./other/merge'); const moduleTransform = require('./module/module'); const pluginsTransform = require('./plugins/plugins'); - const topScopeTransform = require('./topScope/index'); /* @@ -55,7 +55,8 @@ const transformsObject = { profileTransform, moduleTransform, pluginsTransform, - topScopeTransform + topScopeTransform, + mergeTransform }; module.exports = function runTransform(yeomanConfig) { diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index f75040cf525..7fe24e42aab 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -151,6 +151,8 @@ module.exports = function(j, ast, yeomanConfig) { } }); }); + } else { + prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.module[webpackProp]))); } } }); diff --git a/lib/creator/transformations/other/merge.js b/lib/creator/transformations/other/merge.js new file mode 100644 index 00000000000..a4c6a4ae933 --- /dev/null +++ b/lib/creator/transformations/other/merge.js @@ -0,0 +1,33 @@ +module.exports = function(j, ast, yeomanConfig) { + const webpackProperties = yeomanConfig.webpackOptions; + function createMergeProperty(p) { + // FIXME Use j.callExp() + let exportsDecl = p.value.body.map( (n) => { + if(n.expression) { + return n.expression.right; + } + }); + const bodyLength = exportsDecl.length; + let newVal = {}; + newVal.type = 'ExpressionStatement'; + newVal.expression = { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'MemberExpression', + computed: false, + object: j.identifier('module'), + property: j.identifier('exports') + }, + right: j.callExpression( + j.identifier('merge'), + [j.identifier(webpackProperties['merge']), exportsDecl.pop()]) + }; + p.value.body[bodyLength - 1] = newVal; + } + if(webpackProperties['merge']) { + return ast.find(j.Program).filter(p => createMergeProperty(p)); + } else { + return ast; + } +}; From a0244763f7c4a414dfadf1f1ff113f90ffb9f403 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 14 Apr 2017 01:28:07 +0200 Subject: [PATCH 043/101] fix: make build more readable --- .../transformations/context/context.js | 13 +- .../transformations/devtool/devtool.js | 12 +- lib/creator/transformations/entry/entry.js | 46 ++-- .../transformations/externals/externals.js | 120 +++++---- lib/creator/transformations/module/module.js | 237 +++++++----------- lib/creator/transformations/module/utils.js | 120 +++++++++ lib/creator/transformations/node/node.js | 43 ++-- lib/creator/transformations/other/amd.js | 42 ++-- lib/creator/transformations/other/bail.js | 15 +- lib/creator/transformations/other/cache.js | 27 +- lib/creator/transformations/other/profile.js | 15 +- lib/creator/transformations/output/output.js | 66 ++--- .../performance/performance.js | 58 +++-- .../transformations/plugins/plugins.js | 16 +- .../transformations/resolve/resolve.js | 137 +++++----- lib/creator/transformations/stats/stats.js | 55 ++-- lib/creator/transformations/target/target.js | 6 +- lib/creator/transformations/watch/watch.js | 6 +- .../transformations/watch/watchOptions.js | 44 ++-- 19 files changed, 611 insertions(+), 467 deletions(-) create mode 100644 lib/creator/transformations/module/utils.js diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 410b9523d26..898697498e4 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,14 +1,15 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; + function createContextProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push( - j.property('init', j.identifier('context'), j.identifier(webpackProperties['context'])) - ); - } + return p.value.properties.push( + j.property('init', j.identifier('context'), j.identifier(webpackProperties['context'])) + ); } + if(webpackProperties['context'] && webpackProperties['context'].length) { - return ast.find(j.ObjectExpression).filter(p => createContextProperty(p)); + return ast.find(j.ObjectExpression) + .filter(p => createContextProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index e4ed357fdb7..06256ed62bd 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,12 +1,16 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; + function createDevToolProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(j.property('init', j.identifier('devtool'), j.identifier(webpackProperties['devtool']))); - } + return p.value.properties.push( + j.property('init', + j.identifier('devtool'), + j.identifier(webpackProperties['devtool'])) + ); } if(webpackProperties['devtool'] && webpackProperties['devtool'].length) { - return ast.find(j.ObjectExpression).filter(p => createDevToolProperty(p)); + return ast.find(j.ObjectExpression) + .filter(p => createDevToolProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index f245e3edc5b..2f5771a1bba 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,30 +1,32 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; + function createEntryProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('entry'), j.literal('null'))); - p.value.properties.filter(node => node.key.name === 'entry').forEach( (prop) => { - if((webpackProperties['entry'] && webpackProperties['entry'].length)) { - prop.value.value = webpackProperties['entry']; - } - else { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.entry).forEach( (webpackProps) => { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProps), - j.identifier(webpackProperties.entry[webpackProps]) - ) - ); - }); - } - }); - } + let entryNode = p.value.properties; + entryNode.push(j.property('init', j.identifier('entry'), j.literal('null'))); + entryNode.filter(n => n.key.name === 'entry'); + entryNode.forEach( (entryProp) => { + if(webpackProperties['entry'].length) { + entryProp.value.value = webpackProperties['entry']; + } + else { + entryProp.value.type = 'ObjectExpression'; + entryProp.value.properties = []; + Object.keys(webpackProperties['entry']).forEach( (webpackProps) => { + entryProp.value.properties.push( + j.property( + 'init', + j.identifier(webpackProps), + j.identifier(webpackProperties.entry[webpackProps]) + ) + ); + }); + } + }); } if(webpackProperties['entry']) { - return ast.find(j.ObjectExpression).filter(p => createEntryProperty(p)); + return ast.find(j.ObjectExpression) + .filter(p => createEntryProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 126466374da..4307985c917 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -1,56 +1,82 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createExternalProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - if(webpackProperties.externals instanceof RegExp) { - return p.value.properties.push(j.property('init', j.identifier('externals'), j.literal(webpackProperties.externals))); - } - else { - p.value.properties.push(j.property('init', j.identifier('externals'), j.literal('null'))); - } - p.value.properties.filter(node => node.key.name === 'externals').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.externals).forEach( (webpackProp) => { - if(Array.isArray(webpackProperties.externals[webpackProp])) { - // if we got a type, we make it an array - const externalArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); - webpackProperties.externals[webpackProp].forEach( (n) => { - return externalArray.value.elements.push(j.identifier(n)); - }); - prop.value.properties.push(externalArray); - } - else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.externals[webpackProp]))); - } - else { - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); - prop.value.properties.forEach( (externalProp) => { - if(externalProp.key.name === webpackProp) { - externalProp.value.type = 'ObjectExpression'; - externalProp.value.properties = []; - Object.keys(webpackProperties.externals[webpackProp]).forEach( (subProps) => { - if(Array.isArray(webpackProperties.externals[webpackProp][subProps])) { - const subExternalArray = j.property('init', j.identifier(subProps), j.arrayExpression([])); - webpackProperties.externals[webpackProp][subProps].forEach( (n) => { - return subExternalArray.value.elements.push(j.identifier(n)); - }); - externalProp.value.properties.push(subExternalArray); - } else { - externalProp.value.properties.push( - j.property('init', j.identifier(subProps), j.identifier(webpackProperties.externals[webpackProp][subProps])) - ); - } - }); - } - }); - } - }); - }); + if(webpackProperties.externals instanceof RegExp) { + return p.value.properties.push( + j.property('init', j.identifier('externals'), j.literal(webpackProperties.externals)) + ); + } + else { + p.value.properties.push( + j.property('init', j.identifier('externals'), j.objectExpression([])) + ); } + let externalsProp = p.value.properties; + externalsProp.filter(n => n.key.name === 'externals'); + externalsProp.forEach( (prop) => { + Object.keys(webpackProperties['externals']).forEach( (webpackProp) => { + if(Array.isArray(webpackProperties.externals[webpackProp])) { + // if we got a type, we make it an array + const externalArray = j.property( + 'init', + j.identifier(webpackProp), + j.arrayExpression([]) + ); + + webpackProperties.externals[webpackProp].forEach( (n) => { + return externalArray.value.elements.push(j.identifier(n)); + }); + + prop.value.properties.push(externalArray); + } + else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.identifier(webpackProperties.externals[webpackProp])) + ); + } + else { + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.objectExpression([])) + ); + prop.value.properties.forEach( (externalProp) => { + if(externalProp.key.name === webpackProp) { + + Object.keys(webpackProperties.externals[webpackProp]).forEach( (subProps) => { + if(Array.isArray(webpackProperties.externals[webpackProp][subProps])) { + const subExternalArray = j.property( + 'init', + j.identifier(subProps), + j.arrayExpression([]) + ); + + webpackProperties.externals[webpackProp][subProps].forEach( (n) => { + return subExternalArray.value.elements.push(j.identifier(n)); + }); + externalProp.value.properties.push(subExternalArray); + } else { + externalProp.value.properties.push( + j.property( + 'init', + j.identifier(subProps), + j.identifier( + webpackProperties.externals[webpackProp][subProps] + ) + ) + ); + } + }); + } + }); + } + }); + }); } if(webpackProperties['externals'] && typeof webpackProperties['externals'] === 'object') { - return ast.find(j.ObjectExpression).filter(p => createExternalProperty(p)); + return ast.find(j.ObjectExpression) + .filter(p => createExternalProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 7fe24e42aab..19beaf9f53d 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -1,169 +1,110 @@ const webpackModuleTypes = require('./module-types'); +const utils = require('./utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; + function createModuleProperties(p) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('module'), j.literal('null'))); - p.value.properties.filter( node => node.key.name === 'module').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.module).forEach( (webpackProp) => { - if(['noParse', 'rules'].includes(webpackProp)) { - if(webpackProperties.module[webpackProp].__paths) { - let RegExpDec = webpackProperties.module[webpackProp].__paths[0].value.program.body[0].expression; - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(RegExpDec.value)) + p.value.properties.push( + j.property('init', j.identifier('module'), j.objectExpression([])) + ); + + let moduleNode = p.value.properties.filter(n => n.key.name === 'module'); + moduleNode.forEach( (prop) => { + Object.keys(webpackProperties['module']).forEach( (webpackProp) => { + if(['noParse', 'rules'].includes(webpackProp)) { + if(webpackProperties.module[webpackProp].__paths) { + // optional if user can't use regular regexp + utils.regExpStrategy(j, webpackProperties, webpackProp, prop); + } + else if(Array.isArray(webpackProperties.module[webpackProp])) { + const rulesArray = j.property( + 'init', + j.identifier(webpackProp), + j.arrayExpression([]) + ); + prop.value.properties.push(rulesArray); + // Keeps track of what object we're refering to when adding props + let seen = -1; + let rulesProperties = webpackProperties.module[webpackProp]; + + rulesProperties.forEach( (subProps) => { + let rulesMatchProp = prop.value.properties.filter( + n => n.key.name === webpackProp ); - } - else if(Array.isArray(webpackProperties.module[webpackProp])) { - const moduleArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); - prop.value.properties.push(moduleArray); - let seen = -1; - webpackProperties.module[webpackProp].forEach( (subProps) => { - prop.value.properties.filter(n => n.key.name === webpackProp).forEach( moduleProp => { - for(let key in subProps) { - if(key.indexOf('inject') >= 0) { - moduleProp.value.elements.push(subProps[key]); - seen += 1; - } - if(webpackModuleTypes.includes(key)) { - if(key === 'test') { - moduleProp.value.elements.push(j.objectExpression([])); - seen += 1; - moduleProp.value.elements[seen].properties.push( - j.property( - 'init', - j.identifier(key), - j.literal( - subProps[key] - ) - ) - ); - } - if(key === 'enforce') { - moduleProp.value.elements[seen].properties.push( - j.property('init', j.identifier(key), j.identifier(subProps[key])) - ); - } - if(key === 'loader') { - moduleProp.value.elements[seen].properties.push( - j.property('init', j.identifier(key), j.identifier(subProps[key])) - ); - } - if(key === 'options') { - let optionVal = j.property('init', j.identifier(key), j.identifier('presets')); - if(typeof(subProps[key]) === 'string') { - optionVal.value = j.identifier(subProps[key]); - } else { - optionVal.value.type = 'ObjectExpression'; - optionVal.value.properties = []; - Object.keys(subProps[key]).forEach( (optionProperty) => { + rulesMatchProp.forEach( moduleProp => { + for(let key in subProps) { + if(key.indexOf('inject') >= 0) { - if(Array.isArray(subProps[key][optionProperty])) { - const optionArray = j.property( - 'init', - j.identifier(optionProperty), - j.arrayExpression([]) - ); - subProps[key][optionProperty].forEach( (n) => { - optionArray.value.elements.push(j.literal(n)); - }); - optionVal.value.properties.push(optionArray); - } else { - if(typeof(subProps[key][optionProperty]) === 'string') { - optionVal.value.properties.push( - j.property( - 'init', - j.identifier(optionProperty), - j.identifier(subProps[key][optionProperty]) - ) - ); - } else { - optionVal.value.properties.push( - j.property( - 'init', - j.identifier(optionProperty), - j.literal(subProps[key][optionProperty]) - ) - ); - } - } - }); - } - moduleProp.value.elements[seen].properties.push(optionVal); - } - if(key === 'use') { - let UseVal = j.property('init', j.identifier(key), j.arrayExpression([])); + moduleProp.value.elements.push( + subProps[key] + ); - Object.keys(subProps[key]).forEach( (optionProperty) => { - if(typeof(subProps[key][optionProperty]) === 'string') { - UseVal.value.elements.push(j.identifier(subProps[key][optionProperty])); - } else { - let loaderProperty = j.objectExpression([]); + seen += 1; + } - Object.keys(subProps[key][optionProperty]).forEach( subOptionProp => { - if(typeof(subProps[key][optionProperty][subOptionProp]) === 'string') { - loaderProperty.properties.push( - j.property('init', - j.identifier(subOptionProp), - j.identifier(subProps[key][optionProperty][subOptionProp]) - ) - ); - } else { - let subSubProps = j.objectExpression([]); - Object.keys(subProps[key][optionProperty][subOptionProp]).forEach( (underlyingOption) => { - subSubProps.properties.push( - j.property('init', - j.identifier(underlyingOption), - j.identifier( - subProps[key][optionProperty][subOptionProp][underlyingOption] - ) - ) - ); - }); - loaderProperty.properties.push(j.property('init', j.identifier(subOptionProp), subSubProps)); - } - }); - UseVal.value.elements.push(loaderProperty); - } - }); - moduleProp.value.elements[seen].properties.push(UseVal); - } - if(key === 'oneOf') { - // TODO - } - if(key === 'rules') { - // TODO - } - if(key === 'resource') { - // TODO - } - if(key === 'include' || key === 'exclude') { - let InExcludeVal = j.property('init', j.identifier(key), j.arrayExpression([])); - Object.keys(subProps[key]).forEach( (subProperty) => { - InExcludeVal.value.elements.push(j.identifier(subProps[key][subProperty])); - }); - moduleProp.value.elements[seen].properties.push(InExcludeVal); - } + if(webpackModuleTypes.includes(key)) { + if(key === 'test') { + moduleProp.value.elements.push( + j.objectExpression([]) + ); + seen += 1; + utils.createTestProperty(j, moduleProp, seen, key, subProps); + } + if(key === 'enforce' || key === 'loader') { + moduleProp.value.elements[seen].properties.push( + j.property( + 'init', + j.identifier(key), + j.identifier(subProps[key]) + ) + ); + } + if(key === 'options' || key === 'use') { + const subProperties = (key === 'use') ? + utils.createUseProperties(j, key, subProps) : + utils.createOption(j, subProps, key); + moduleProp.value.elements[seen].properties.push( + subProperties + ); + } + if(key === 'oneOf') { + // TODO + } + if(key === 'rules') { + // TODO + } + if(key === 'resource') { + // TODO + } + if(key === 'include' || key === 'exclude') { + moduleProp.value.elements[seen].properties.push( + utils.createIncludeOrExcludeProperties(j, key, subProps) + ); } } - }); + } }); - } else { - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.module[webpackProp]))); - } + }); + } else { + // module.rules is an external object + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.identifier(webpackProperties.module[webpackProp]) + ) + ); } - }); + } }); - } + }); } if(!webpackProperties['module']) { return ast; - } else if(webpackProperties['module'].length) { - throw new Error('Supplying output with only no options is not supported.'); } else { - return ast.find(j.ObjectExpression).filter(p => createModuleProperties(p)); + return ast.find(j.ObjectExpression) + .filter(p => createModuleProperties(p)); } }; diff --git a/lib/creator/transformations/module/utils.js b/lib/creator/transformations/module/utils.js new file mode 100644 index 00000000000..39634eab720 --- /dev/null +++ b/lib/creator/transformations/module/utils.js @@ -0,0 +1,120 @@ + +// optional for the user to parse using jscodeshift for only this if a regular regexp doesnt work. +function regExpStrategy(j, webpackProperties, webpackProp, prop) { + let RegExpDec = webpackProperties.module[webpackProp].__paths[0].value.program.body[0].expression; + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.literal(RegExpDec.value)) + ); +} + +// Module.rules.myRule.test +function createTestProperty(j, moduleProp, seen, key, subProps) { + moduleProp.value.elements[seen].properties.push( + j.property( + 'init', + j.identifier(key), + j.literal( + subProps[key] + ) + ) + ); +} +// Module.rules.myRule.option +function createOption(j, subProps, key) { + let optionVal = j.property('init', j.identifier(key), j.identifier('null')); + + if(typeof(subProps[key]) === 'string') { + optionVal.value = j.identifier(subProps[key]); + } else { + optionVal.value.type = 'ObjectExpression'; + optionVal.value.properties = []; + Object.keys(subProps[key]).forEach( (optionProperty) => { + if(Array.isArray(subProps[key][optionProperty])) { + const optionArray = j.property( + 'init', + j.identifier(optionProperty), + j.arrayExpression([]) + ); + subProps[key][optionProperty].forEach( (n) => { + optionArray.value.elements.push(j.literal(n)); + }); + optionVal.value.properties.push(optionArray); + } else { + if(typeof(subProps[key][optionProperty]) === 'string') { + optionVal.value.properties.push( + j.property( + 'init', + j.identifier(optionProperty), + j.identifier(subProps[key][optionProperty]) + ) + ); + } else { + optionVal.value.properties.push( + j.property( + 'init', + j.identifier(optionProperty), + j.literal(subProps[key][optionProperty]) + ) + ); + } + } + }); + } + return optionVal; +} +// Module.rules.rule.use +function createUseProperties(j, key, subProps) { + let useVal = j.property('init', j.identifier(key), j.arrayExpression([])); + + Object.keys(subProps[key]).forEach( (optionProperty) => { + if(typeof(subProps[key][optionProperty]) === 'string') { + useVal.value.elements.push( + j.identifier(subProps[key][optionProperty]) + ); + } else { + let loaderProperty = j.objectExpression([]); + Object.keys(subProps[key][optionProperty]).forEach( subOptionProp => { + if(typeof(subProps[key][optionProperty][subOptionProp]) === 'string') { + loaderProperty.properties.push( + j.property('init', + j.identifier(subOptionProp), + j.identifier(subProps[key][optionProperty][subOptionProp]) + )); + } else { + let subSubProps = j.objectExpression([]); + Object.keys(subProps[key][optionProperty][subOptionProp]).forEach( (underlyingOption) => { + subSubProps.properties.push( + j.property('init', + j.identifier(underlyingOption), + j.identifier( + subProps[key][optionProperty][subOptionProp][underlyingOption] + )) + ); + }); + loaderProperty.properties.push( + j.property('init', j.identifier(subOptionProp), subSubProps) + ); + } + }); + useVal.value.elements.push(loaderProperty); + } + }); + return useVal; +} + +// Module.rules.include/exclude +function createIncludeOrExcludeProperties(j, key, subProps) { + let InExcludeVal = j.property('init', j.identifier(key), j.arrayExpression([])); + Object.keys(subProps[key]).forEach( (subProperty) => { + InExcludeVal.value.elements.push(j.identifier(subProps[key][subProperty])); + }); + return InExcludeVal; +} + +module.exports = { + regExpStrategy, + createTestProperty, + createOption, + createUseProperties, + createIncludeOrExcludeProperties +}; diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index f40261c7cf1..fac7ba446d4 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -1,27 +1,34 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createNodeProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('node'), j.literal('null'))); - p.value.properties.filter(node => node.key.name === 'node').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.node).forEach( (webpackProp) => { - if(typeof(webpackProperties.node[webpackProp]) === 'boolean') { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.node[webpackProp])) - ); - } else { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.node[webpackProp])) - ); - } - }); + let node = p.value.properties; + node.push(j.property('init', j.identifier('node'), j.objectExpression([]))); + node.filter(n => n.key.name === 'node').forEach( (prop) => { + Object.keys(webpackProperties.node).forEach( (webpackProp) => { + if(typeof(webpackProperties.node[webpackProp]) === 'boolean') { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.literal(webpackProperties.node[webpackProp]) + ) + ); + } else { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.identifier(webpackProperties.node[webpackProp] + ) + ) + ); + } }); - } + }); } if(webpackProperties['node'] && typeof(webpackProperties['node']) === 'object') { - return ast.find(j.ObjectExpression).filter(p => createNodeProperty(p)); + return ast.find(j.ObjectExpression) + .filter(p => createNodeProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index 5dc90818c05..38d472fd6ed 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -1,27 +1,33 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createAMDProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('amd'), j.literal('null'))); - p.value.properties.filter(node => node.key.name === 'amd').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.amd).forEach( (webpackProp) => { - if(typeof(webpackProperties.amd[webpackProp]) === 'boolean') { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.amd[webpackProp])) - ); - } else { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.amd[webpackProp])) - ); - } - }); + let amdNode = p.value.properties; + amdNode.push(j.property('init', j.identifier('amd'), j.objectExpression([]))); + amdNode.filter(n => n.key.name === 'amd').forEach( (prop) => { + Object.keys(webpackProperties['amd']).forEach( (webpackProp) => { + if(typeof(webpackProperties.amd[webpackProp]) === 'boolean') { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.literal(webpackProperties.amd[webpackProp]) + ) + ); + } else { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.identifier(webpackProperties.amd[webpackProp]) + ) + ); + } }); - } + }); } if(webpackProperties['amd'] && typeof(webpackProperties['amd']) === 'object') { - return ast.find(j.ObjectExpression).filter(p => createAMDProperty(p)); + return ast.find(j.ObjectExpression) + .filter(p => createAMDProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index f6144393e56..b9becbdd269 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,14 +1,15 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; + function createBailProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - let bailVal = (typeof webpackProperties['bail'] === 'boolean') - ? j.literal(webpackProperties['bail']) : j.identifier(webpackProperties['bail']); - p.value.properties.push(j.property('init', j.identifier('bail'), bailVal)); - } + let bailVal = (typeof webpackProperties['bail'] === 'boolean') ? + j.literal(webpackProperties['bail']) : j.identifier(webpackProperties['bail']); + p.value.properties.push(j.property('init', j.identifier('bail'), bailVal)); } - if(typeof(webpackProperties['bail']) === 'boolean') { - return ast.find(j.ObjectExpression).filter(p => createBailProperty(p)); + + if(webpackProperties['bail']) { + return ast.find(j.ObjectExpression) + .filter(p => createBailProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index 36749dc329a..e5d82d1ab48 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,23 +1,20 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createCacheProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - if(webpackProperties['cache']) { - return p.value.properties.push( - j.property('init', j.identifier('cache'), j.identifier(webpackProperties['cache'])) - ); - } + if(typeof(webpackProperties['cache']) === 'object') { + return p.value.properties.push( + j.property('init', j.identifier('cache'), j.identifier(webpackProperties['cache'])) + ); + } else { + p.value.properties.push( + j.property('init', j.identifier('cache'), j.literal(webpackProperties['cache'])) + ); } } - if(typeof(webpackProperties['cache']) === 'boolean') { - return ast.find(j.ObjectExpression).filter(p => { - if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(j.property('init', j.identifier('cache'), j.literal(webpackProperties['cache']))); - } - }); - } - else if(webpackProperties['cache'] && typeof(webpackProperties['cache']) === 'object') { - return ast.find(j.ObjectExpression).filter(p => createCacheProperty(p)); + + if(webpackProperties['cache']) { + return ast.find(j.ObjectExpression) + .filter(p => createCacheProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index 994f1501d5a..ef681b4a5fd 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,12 +1,19 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createProfileProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('profile'), j.identifier(webpackProperties['profile']))); + if(typeof(webpackProperties['profile']) === 'boolean') { + return p.value.properties.push( + j.property('init', j.identifier('profile'), j.literal(webpackProperties['profile'])) + ); + } else { + return p.value.properties.push( + j.property('init', j.identifier('profile'), j.identifier(webpackProperties['profile'])) + ); } } - if(typeof(webpackProperties['profile']) === 'boolean') { - return ast.find(j.ObjectExpression).filter(p => createProfileProperty(p)); + if(webpackProperties['profile']) { + return ast.find(j.ObjectExpression) + .filter(p => createProfileProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 8935c67a2fe..be4a4119fd8 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -3,39 +3,45 @@ const webpackOutputTypes = require('./output-types'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createOutputProperties(p) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('output'), j.objectExpression([]))); - p.value.properties.filter( node => node.key.name === 'output').forEach( (prop) => { - Object.keys(webpackProperties.output).forEach( (webpackProp) => { - if(webpackOutputTypes.includes(webpackProp)) { - if(typeof webpackProperties.output[webpackProp] === 'boolean') { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.output[webpackProp])) - ); - } - else if(webpackProperties.output[webpackProp].__paths) { - let regExpProp = webpackProperties.output[webpackProp].__paths[0].value.program.body[0].expression; - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(regExpProp.value)) - ); - } - else { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.output[webpackProp])) - ); - } - } else { - return ast; + let outputNode = p.value.properties; + outputNode.push(j.property('init', j.identifier('output'), j.objectExpression([]))); + outputNode.filter( n => n.key.name === 'output'); + outputNode.forEach( (prop) => { + Object.keys(webpackProperties.output).forEach( (webpackProp) => { + if(webpackOutputTypes.includes(webpackProp)) { + if(typeof webpackProperties.output[webpackProp] === 'boolean') { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.literal(webpackProperties.output[webpackProp]) + ) + ); } - }); + else if(webpackProperties.output[webpackProp].__paths) { + let regExpProp = + webpackProperties.output[webpackProp].__paths[0].value.program.body[0].expression; + + prop.value.properties.push( + j.property('init', j.identifier(webpackProp), j.literal(regExpProp.value)) + ); + } + else { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.identifier(webpackProperties.output[webpackProp]) + ) + ); + } + } }); - } + }); } - if(!webpackProperties['output']) { - return ast; - } else if(webpackProperties['output'].length) { - throw new Error('Supplying output with only no options is not supported.'); - } else { + if(webpackProperties['output']) { return ast.find(j.ObjectExpression).filter(p => createOutputProperties(p)); + } else { + return ast; } }; diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 416c011f5e3..515f0812634 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -2,39 +2,43 @@ const performanceTypes = require('./performance-types'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; + function createPerformanceProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('performance'), j.literal('null'))); - p.value.properties.filter(node => node.key.name === 'performance').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.performance).forEach( (webpackProp) => { - if(performanceTypes.includes(webpackProp)) { - if(Array.isArray(webpackProperties.performance[webpackProp])) { - throw new Error('Unknown Property', webpackProp); - } - else { - if(typeof(webpackProperties.performance[webpackProp]) == 'string') { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.identifier(webpackProperties.performance[webpackProp]) - ) - ); - } else { - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.performance[webpackProp]))); - } - } - } else { + let performanceNode = p.value.properties; + performanceNode.push(j.property('init', j.identifier('performance'), j.objectExpression([]))); + performanceNode.filter(n => n.key.name === 'performance'); + performanceNode.forEach( (prop) => { + Object.keys(webpackProperties.performance).forEach( (webpackProp) => { + if(performanceTypes.includes(webpackProp)) { + if(Array.isArray(webpackProperties.performance[webpackProp])) { throw new Error('Unknown Property', webpackProp); } - }); + else { + if(typeof(webpackProperties.performance[webpackProp]) == 'string') { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.identifier(webpackProperties.performance[webpackProp]) + ) + ); + } else { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.literal(webpackProperties.performance[webpackProp]) + ) + ); + } + } + } }); - } + }); } if(webpackProperties['performance'] && typeof(webpackProperties['performance']) === 'object') { - return ast.find(j.ObjectExpression).filter(p => createPerformanceProperty(p)); + return ast.find(j.ObjectExpression) + .filter(p => createPerformanceProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index c2797a20973..fe75ee2b971 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -2,15 +2,13 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createPluginsProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - const pluginArray = j.property('init', j.identifier('plugins'), j.arrayExpression([])); - Object.keys(webpackProperties.plugins).forEach( (plugin) => { - if(webpackProperties.plugins[plugin]) { - pluginArray.value.elements.push(webpackProperties.plugins[plugin]); - } - }); - return p.value.properties.push(pluginArray); - } + const pluginArray = j.property('init', j.identifier('plugins'), j.arrayExpression([])); + Object.keys(webpackProperties.plugins).forEach( (plugin) => { + if(webpackProperties.plugins[plugin]) { + pluginArray.value.elements.push(j.identifier(webpackProperties.plugins[plugin])); + } + }); + return p.value.properties.push(pluginArray); } if(webpackProperties['plugins'] && Array.isArray(webpackProperties['plugins'])) { return ast.find(j.ObjectExpression).filter(p => createPluginsProperty(p)); diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index ed86068f9f0..99c2734c77d 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -3,72 +3,83 @@ const resolveTypes = require('./resolve-types'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createResolveProperties(p) { - if(webpackProperties['resolve']) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('resolve'), j.literal('null'))); - } - p.value.properties.filter(node => node.key.name === 'resolve').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.resolve).forEach( (webpackProp) => { - if(resolveTypes.includes(webpackProp) || webpackProp === 'resolveLoader') { - if(Array.isArray(webpackProperties.resolve[webpackProp])) { - // if we got a type, we make it an array - const resolveArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); - webpackProperties.resolve[webpackProp].forEach( (n) => { - return resolveArray.value.elements.push(j.identifier(n)); - }); - prop.value.properties.push(resolveArray); - } - else if(typeof(webpackProperties.resolve[webpackProp]) === 'boolean') { - let boolExp = j.property('init', j.identifier(webpackProp), j.literal(webpackProperties.resolve[webpackProp])); - prop.value.properties.push(boolExp); - } - else { - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.literal('null'))); - prop.value.properties.forEach( (resolveProp) => { - if(resolveProp.key.name === webpackProp) { - resolveProp.value.type = 'ObjectExpression'; - resolveProp.value.properties = []; - if(resolveProp.key.name === 'cachePredicate') { - let cachePredicateVal = (typeof webpackProperties.resolve[webpackProp] === 'string') ? - j.identifier(webpackProperties.resolve[webpackProp]) : - j.literal(webpackProperties.resolve[webpackProp]); - resolveProp.value = cachePredicateVal; + let resolveNode = p.value.properties; + resolveNode.push(j.property('init', j.identifier('resolve'), j.objectExpression([]))); + resolveNode.filter(n => n.key.name === 'resolve'); + resolveNode.forEach( (prop) => { + Object.keys(webpackProperties.resolve).forEach( (webpackProp) => { + if(resolveTypes.includes(webpackProp) || webpackProp === 'resolveLoader') { + if(Array.isArray(webpackProperties.resolve[webpackProp])) { + // if we got a type, we make it an array + const resolveArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); + webpackProperties.resolve[webpackProp].forEach( (n) => { + return resolveArray.value.elements.push(j.identifier(n)); + }); + prop.value.properties.push(resolveArray); + } + else if(typeof(webpackProperties.resolve[webpackProp]) === 'boolean') { + let boolExp = j.property( + 'init', + j.identifier(webpackProp), + j.literal(webpackProperties.resolve[webpackProp]) + ); + prop.value.properties.push(boolExp); + } + else { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.objectExpression([])) + ); + prop.value.properties.forEach( (resolveProp) => { + if(resolveProp.key.name === webpackProp) { + if(resolveProp.key.name === 'cachePredicate') { + let cachePredicateVal = + (typeof webpackProperties.resolve[webpackProp] === 'string') ? + j.identifier(webpackProperties.resolve[webpackProp]) : + j.literal(webpackProperties.resolve[webpackProp]); + resolveProp.value = cachePredicateVal; + } + Object.keys(webpackProperties.resolve[webpackProp]).forEach( (aliasProps) => { + if(Array.isArray(webpackProperties.resolve[webpackProp][aliasProps])) { + const resolveLoaderArray = j.property( + 'init', + j.identifier(aliasProps), + j.arrayExpression([]) + ); + webpackProperties.resolve[webpackProp][aliasProps].forEach( (n) => { + return resolveLoaderArray.value.elements.push(j.identifier(n)); + }); + resolveProp.value.properties.push(resolveLoaderArray); - } - Object.keys(webpackProperties.resolve[webpackProp]).forEach( (aliasProps) => { - if(Array.isArray(webpackProperties.resolve[webpackProp][aliasProps])) { - const resolveLoaderArray = j.property('init', j.identifier(aliasProps), j.arrayExpression([])); - webpackProperties.resolve[webpackProp][aliasProps].forEach( (n) => { - return resolveLoaderArray.value.elements.push(j.identifier(n)); - }); - resolveProp.value.properties.push(resolveLoaderArray); - } else if(webpackProperties.resolve[webpackProp][aliasProps].length > 1) { - if(aliasProps.indexOf('inject') >= 0) { - resolveProp.value.properties.push(j.identifier( - webpackProperties.resolve[webpackProp][aliasProps] - )); - } else { - resolveProp.value.properties.push( - j.property('init', j.identifier(aliasProps), j.identifier(webpackProperties.resolve[webpackProp][aliasProps])) - ); - } + } else if(webpackProperties.resolve[webpackProp][aliasProps].length > 1) { + if(aliasProps.indexOf('inject') >= 0) { + resolveProp.value.properties.push(j.identifier( + webpackProperties.resolve[webpackProp][aliasProps] + )); + } else { + resolveProp.value.properties.push( + j.property( + 'init', + j.identifier(aliasProps), + j.identifier(webpackProperties.resolve[webpackProp][aliasProps]) + ) + ); } - }); - } - }); - } + } + }); + } + }); } - }); + } }); - } - else if(webpackProperties['resolve'] && webpackProperties['resolve'].length) { - throw new Error('Resolve needs properties'); - } - else { - return ast; - } + }); + } + if(webpackProperties['resolve'] ) { + return ast.find(j.ObjectExpression).filter(p => createResolveProperties(p)); + } + else { + return ast; } - return ast.find(j.ObjectExpression).filter(p => createResolveProperties(p)); }; diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index 634fa1e8fed..12249a53d55 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -3,38 +3,45 @@ const statsTypes = require('./stats-types'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createStatsProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('stats'), j.literal('null'))); - p.value.properties.filter(node => node.key.name === 'stats').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties.stats).forEach( (webpackProp) => { - if(statsTypes.includes(webpackProp)) { - if(Array.isArray(webpackProperties.stats[webpackProp])) { - const statsArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); - webpackProperties.stats[webpackProp].forEach( (n) => { - return statsArray.value.elements.push(j.literal(n)); - }); - prop.value.properties.push(statsArray); - } - else { - prop.value.properties.push(j.property('init', j.identifier(webpackProp), j.identifier(webpackProperties.stats[webpackProp]))); - } - } else { - throw new Error('Unknown Property', webpackProp); + let statsNode = p.value.properties; + statsNode.push(j.property('init', j.identifier('stats'), j.objectExpression([]))); + statsNode.filter(n => n.key.name === 'stats'); + statsNode.forEach( (prop) => { + Object.keys(webpackProperties.stats).forEach( (webpackProp) => { + if(statsTypes.includes(webpackProp)) { + if(Array.isArray(webpackProperties.stats[webpackProp])) { + const statsArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); + webpackProperties.stats[webpackProp].forEach( (n) => { + return statsArray.value.elements.push(j.identifier(n)); + }); + prop.value.properties.push(statsArray); } - }); + else { + prop.value.properties.push( + j.property( + 'init', + j.identifier(webpackProp), + j.identifier(webpackProperties.stats[webpackProp]) + ) + ); + } + } else { + throw new Error('Unknown Property', webpackProp); + } }); - } + }); } if(webpackProperties['stats'] && typeof(webpackProperties['stats']) === 'object') { return ast.find(j.ObjectExpression).filter(p => createStatsProperty(p)); } + // FIXME -> HOC AssignmentExpression else if(webpackProperties['stats'] && webpackProperties['stats'].length) { return ast.find(j.ObjectExpression).filter(p => { - if(p.parent.value.type === 'AssignmentExpression') - return p.value.properties.push(j.property('init', j.identifier('stats'), j.identifier(webpackProperties['stats']))); - + if(p.parent.value.type === 'AssignmentExpression') { + return p.value.properties.push( + j.property('init', j.identifier('stats'), j.identifier(webpackProperties['stats'])) + ); + } }); } else { return ast; diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 312bbb6087d..5095c53a302 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,9 +1,9 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createTargetProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(j.property('init', j.identifier('target'), j.identifier(webpackProperties['target']))); - } + return p.value.properties.push( + j.property('init', j.identifier('target'), j.identifier(webpackProperties['target'])) + ); } if(webpackProperties['target'] && webpackProperties['target'].length) { return ast.find(j.ObjectExpression).filter(p => createTargetProperty(p)); diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 563f57b67f8..d43fa7d720e 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,9 +1,9 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push(j.property('init', j.identifier('watch'), j.literal(webpackProperties['watch']))); - } + return p.value.properties.push( + j.property('init', j.identifier('watch'), j.literal(webpackProperties['watch'])) + ); } if(typeof(webpackProperties['watch']) === 'boolean') { return ast.find(j.ObjectExpression).filter(p => createWatchProperty(p)); diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index 094e7bd349f..eebb153e026 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -3,28 +3,34 @@ const watchOptionTypes = require('./watchOptions-types'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchOptionsProperty(p) { - if(p.parent.value.type === 'AssignmentExpression') { - p.value.properties.push(j.property('init', j.identifier('watchOptions'), j.literal('null'))); - p.value.properties.filter(node => node.key.name === 'watchOptions').forEach( (prop) => { - prop.value.type = 'ObjectExpression'; - prop.value.properties = []; - Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { - if(watchOptionTypes.includes(watchOption)) { - if(typeof(webpackProperties['watchOptions'][watchOption]) === 'number') { - prop.value.properties.push( - j.property('init', j.identifier(watchOption), j.literal(webpackProperties['watchOptions'][watchOption])) - ); - } else { - prop.value.properties.push( - j.property('init', j.identifier(watchOption), j.identifier(webpackProperties['watchOptions'][watchOption])) - ); - } + let watchOptionsNode = p.value.properties; + watchOptionsNode.push(j.property('init', j.identifier('watchOptions'), j.objectExpression([]))); + watchOptionsNode.filter(n => n.key.name === 'watchOptions'); + watchOptionsNode.forEach( (prop) => { + Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { + if(watchOptionTypes.includes(watchOption)) { + if(typeof(webpackProperties['watchOptions'][watchOption]) === 'number') { + prop.value.properties.push( + j.property( + 'init', + j.identifier(watchOption), + j.literal(webpackProperties['watchOptions'][watchOption]) + ) + ); } else { - throw new Error('Unknown Property', watchOption); + prop.value.properties.push( + j.property( + 'init', + j.identifier(watchOption), + j.identifier(webpackProperties['watchOptions'][watchOption]) + ) + ); } - }); + } else { + throw new Error('Unknown Property', watchOption); + } }); - } + }); } if(webpackProperties['watchOptions'] && webpackProperties['watchOptions']) { return ast.find(j.ObjectExpression).filter(p => createWatchOptionsProperty(p)); From b435585c1fa8b1e036ddb233e71b430c873d461c Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 14 Apr 2017 14:52:31 +0200 Subject: [PATCH 044/101] feat: add HOC to each transform --- lib/creator/transformations/context/context.js | 3 ++- lib/creator/transformations/devtool/devtool.js | 4 +++- lib/creator/transformations/entry/entry.js | 7 ++++--- lib/creator/transformations/externals/externals.js | 7 ++++--- lib/creator/transformations/module/module.js | 7 ++++--- lib/creator/transformations/node/node.js | 4 +++- lib/creator/transformations/other/amd.js | 4 +++- lib/creator/transformations/other/bail.js | 4 +++- lib/creator/transformations/other/cache.js | 4 +++- lib/creator/transformations/other/merge.js | 4 +++- lib/creator/transformations/other/profile.js | 4 +++- lib/creator/transformations/output/output.js | 7 ++++--- lib/creator/transformations/performance/performance.js | 6 +++--- lib/creator/transformations/plugins/plugins.js | 3 ++- lib/creator/transformations/resolve/resolve.js | 6 +++--- lib/creator/transformations/stats/stats.js | 6 +++--- lib/creator/transformations/target/target.js | 4 +++- lib/creator/transformations/watch/watch.js | 4 +++- lib/creator/transformations/watch/watchOptions.js | 6 +++--- lib/creator/utils/is-assignment.js | 5 +++++ 20 files changed, 64 insertions(+), 35 deletions(-) create mode 100644 lib/creator/utils/is-assignment.js diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 898697498e4..5036fa4c2f2 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,3 +1,4 @@ +const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; @@ -9,7 +10,7 @@ module.exports = function(j, ast, yeomanConfig) { if(webpackProperties['context'] && webpackProperties['context'].length) { return ast.find(j.ObjectExpression) - .filter(p => createContextProperty(p)); + .filter(p => isAssignment(p, createContextProperty)); } else { return ast; } diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index 06256ed62bd..a0903e0f724 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; @@ -10,7 +12,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['devtool'] && webpackProperties['devtool'].length) { return ast.find(j.ObjectExpression) - .filter(p => createDevToolProperty(p)); + .filter(p => isAssignment(p, createDevToolProperty)); } else { return ast; } diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 2f5771a1bba..4c59466077c 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,11 +1,12 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createEntryProperty(p) { let entryNode = p.value.properties; entryNode.push(j.property('init', j.identifier('entry'), j.literal('null'))); - entryNode.filter(n => n.key.name === 'entry'); - entryNode.forEach( (entryProp) => { + entryNode.filter(n => n.key.name === 'entry').forEach( (entryProp) => { if(webpackProperties['entry'].length) { entryProp.value.value = webpackProperties['entry']; } @@ -26,7 +27,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['entry']) { return ast.find(j.ObjectExpression) - .filter(p => createEntryProperty(p)); + .filter(p => isAssignment(p, createEntryProperty)); } else { return ast; } diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 4307985c917..e79f356d139 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createExternalProperty(p) { @@ -12,8 +14,7 @@ module.exports = function(j, ast, yeomanConfig) { ); } let externalsProp = p.value.properties; - externalsProp.filter(n => n.key.name === 'externals'); - externalsProp.forEach( (prop) => { + externalsProp.filter(n => n.key.name === 'externals').forEach( (prop) => { Object.keys(webpackProperties['externals']).forEach( (webpackProp) => { if(Array.isArray(webpackProperties.externals[webpackProp])) { // if we got a type, we make it an array @@ -76,7 +77,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['externals'] && typeof webpackProperties['externals'] === 'object') { return ast.find(j.ObjectExpression) - .filter(p => createExternalProperty(p)); + .filter(p => isAssignment(p, createExternalProperty)); } else { return ast; } diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 19beaf9f53d..4cc2556b1e8 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -1,4 +1,5 @@ const webpackModuleTypes = require('./module-types'); +const isAssignment = require('../../utils/is-assignment'); const utils = require('./utils'); module.exports = function(j, ast, yeomanConfig) { @@ -9,8 +10,8 @@ module.exports = function(j, ast, yeomanConfig) { j.property('init', j.identifier('module'), j.objectExpression([])) ); - let moduleNode = p.value.properties.filter(n => n.key.name === 'module'); - moduleNode.forEach( (prop) => { + let moduleNode = p.value.properties; + moduleNode.filter(n => n.key.name === 'module').forEach( (prop) => { Object.keys(webpackProperties['module']).forEach( (webpackProp) => { if(['noParse', 'rules'].includes(webpackProp)) { if(webpackProperties.module[webpackProp].__paths) { @@ -105,6 +106,6 @@ module.exports = function(j, ast, yeomanConfig) { return ast; } else { return ast.find(j.ObjectExpression) - .filter(p => createModuleProperties(p)); + .filter(p => isAssignment(p, createModuleProperties)); } }; diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index fac7ba446d4..53fb84a15e1 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createNodeProperty(p) { @@ -28,7 +30,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['node'] && typeof(webpackProperties['node']) === 'object') { return ast.find(j.ObjectExpression) - .filter(p => createNodeProperty(p)); + .filter(p => isAssignment(p, createNodeProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index 38d472fd6ed..1f71e252b57 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createAMDProperty(p) { @@ -27,7 +29,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['amd'] && typeof(webpackProperties['amd']) === 'object') { return ast.find(j.ObjectExpression) - .filter(p => createAMDProperty(p)); + .filter(p => isAssignment(p, createAMDProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index b9becbdd269..ce65568a827 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; @@ -9,7 +11,7 @@ module.exports = function(j, ast, yeomanConfig) { if(webpackProperties['bail']) { return ast.find(j.ObjectExpression) - .filter(p => createBailProperty(p)); + .filter(p => isAssignment(p, createBailProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index e5d82d1ab48..d939bdfe95c 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createCacheProperty(p) { @@ -14,7 +16,7 @@ module.exports = function(j, ast, yeomanConfig) { if(webpackProperties['cache']) { return ast.find(j.ObjectExpression) - .filter(p => createCacheProperty(p)); + .filter(p => isAssignment(p, createCacheProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/merge.js b/lib/creator/transformations/other/merge.js index a4c6a4ae933..59b404e5ace 100644 --- a/lib/creator/transformations/other/merge.js +++ b/lib/creator/transformations/other/merge.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createMergeProperty(p) { @@ -26,7 +28,7 @@ module.exports = function(j, ast, yeomanConfig) { p.value.body[bodyLength - 1] = newVal; } if(webpackProperties['merge']) { - return ast.find(j.Program).filter(p => createMergeProperty(p)); + return ast.find(j.Program).filter(p => isAssignment(p, createMergeProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index ef681b4a5fd..52dca089230 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createProfileProperty(p) { @@ -13,7 +15,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['profile']) { return ast.find(j.ObjectExpression) - .filter(p => createProfileProperty(p)); + .filter(p => isAssignment(p, createProfileProperty)); } else { return ast; } diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index be4a4119fd8..d1cdcdb8e57 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -1,12 +1,13 @@ const webpackOutputTypes = require('./output-types'); +const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createOutputProperties(p) { let outputNode = p.value.properties; outputNode.push(j.property('init', j.identifier('output'), j.objectExpression([]))); - outputNode.filter( n => n.key.name === 'output'); - outputNode.forEach( (prop) => { + + outputNode.filter( n => n.key.name === 'output').forEach( (prop) => { Object.keys(webpackProperties.output).forEach( (webpackProp) => { if(webpackOutputTypes.includes(webpackProp)) { if(typeof webpackProperties.output[webpackProp] === 'boolean') { @@ -40,7 +41,7 @@ module.exports = function(j, ast, yeomanConfig) { }); } if(webpackProperties['output']) { - return ast.find(j.ObjectExpression).filter(p => createOutputProperties(p)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createOutputProperties)); } else { return ast; } diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 515f0812634..5b403f1a15f 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -1,4 +1,5 @@ const performanceTypes = require('./performance-types'); +const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; @@ -6,8 +7,7 @@ module.exports = function(j, ast, yeomanConfig) { function createPerformanceProperty(p) { let performanceNode = p.value.properties; performanceNode.push(j.property('init', j.identifier('performance'), j.objectExpression([]))); - performanceNode.filter(n => n.key.name === 'performance'); - performanceNode.forEach( (prop) => { + performanceNode.filter(n => n.key.name === 'performance').forEach( (prop) => { Object.keys(webpackProperties.performance).forEach( (webpackProp) => { if(performanceTypes.includes(webpackProp)) { if(Array.isArray(webpackProperties.performance[webpackProp])) { @@ -38,7 +38,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['performance'] && typeof(webpackProperties['performance']) === 'object') { return ast.find(j.ObjectExpression) - .filter(p => createPerformanceProperty(p)); + .filter(p => isAssignment(p, createPerformanceProperty)); } else { return ast; } diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index fe75ee2b971..6d0fb89cfef 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -1,3 +1,4 @@ +const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; @@ -11,7 +12,7 @@ module.exports = function(j, ast, yeomanConfig) { return p.value.properties.push(pluginArray); } if(webpackProperties['plugins'] && Array.isArray(webpackProperties['plugins'])) { - return ast.find(j.ObjectExpression).filter(p => createPluginsProperty(p)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createPluginsProperty)); } else { return ast; } diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index 99c2734c77d..9e1e7cc964e 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -1,12 +1,12 @@ const resolveTypes = require('./resolve-types'); +const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createResolveProperties(p) { let resolveNode = p.value.properties; resolveNode.push(j.property('init', j.identifier('resolve'), j.objectExpression([]))); - resolveNode.filter(n => n.key.name === 'resolve'); - resolveNode.forEach( (prop) => { + resolveNode.filter(n => n.key.name === 'resolve').forEach( (prop) => { Object.keys(webpackProperties.resolve).forEach( (webpackProp) => { if(resolveTypes.includes(webpackProp) || webpackProp === 'resolveLoader') { if(Array.isArray(webpackProperties.resolve[webpackProp])) { @@ -77,7 +77,7 @@ module.exports = function(j, ast, yeomanConfig) { }); } if(webpackProperties['resolve'] ) { - return ast.find(j.ObjectExpression).filter(p => createResolveProperties(p)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createResolveProperties)); } else { return ast; diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index 12249a53d55..9e19ad95224 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -1,12 +1,12 @@ const statsTypes = require('./stats-types'); +const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createStatsProperty(p) { let statsNode = p.value.properties; statsNode.push(j.property('init', j.identifier('stats'), j.objectExpression([]))); - statsNode.filter(n => n.key.name === 'stats'); - statsNode.forEach( (prop) => { + statsNode.filter(n => n.key.name === 'stats').forEach( (prop) => { Object.keys(webpackProperties.stats).forEach( (webpackProp) => { if(statsTypes.includes(webpackProp)) { if(Array.isArray(webpackProperties.stats[webpackProp])) { @@ -32,7 +32,7 @@ module.exports = function(j, ast, yeomanConfig) { }); } if(webpackProperties['stats'] && typeof(webpackProperties['stats']) === 'object') { - return ast.find(j.ObjectExpression).filter(p => createStatsProperty(p)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createStatsProperty)); } // FIXME -> HOC AssignmentExpression else if(webpackProperties['stats'] && webpackProperties['stats'].length) { diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 5095c53a302..1a9d0da2c98 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createTargetProperty(p) { @@ -6,7 +8,7 @@ module.exports = function(j, ast, yeomanConfig) { ); } if(webpackProperties['target'] && webpackProperties['target'].length) { - return ast.find(j.ObjectExpression).filter(p => createTargetProperty(p)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createTargetProperty)); } else { return ast; } diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index d43fa7d720e..2e23c0c2616 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,3 +1,5 @@ +const isAssignment = require('../../utils/is-assignment'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchProperty(p) { @@ -6,7 +8,7 @@ module.exports = function(j, ast, yeomanConfig) { ); } if(typeof(webpackProperties['watch']) === 'boolean') { - return ast.find(j.ObjectExpression).filter(p => createWatchProperty(p)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchProperty)); } else { return ast; } diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index eebb153e026..6d2bc984410 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -1,12 +1,12 @@ const watchOptionTypes = require('./watchOptions-types'); +const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchOptionsProperty(p) { let watchOptionsNode = p.value.properties; watchOptionsNode.push(j.property('init', j.identifier('watchOptions'), j.objectExpression([]))); - watchOptionsNode.filter(n => n.key.name === 'watchOptions'); - watchOptionsNode.forEach( (prop) => { + watchOptionsNode.filter(n => n.key.name === 'watchOptions').forEach( (prop) => { Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { if(watchOptionTypes.includes(watchOption)) { if(typeof(webpackProperties['watchOptions'][watchOption]) === 'number') { @@ -33,7 +33,7 @@ module.exports = function(j, ast, yeomanConfig) { }); } if(webpackProperties['watchOptions'] && webpackProperties['watchOptions']) { - return ast.find(j.ObjectExpression).filter(p => createWatchOptionsProperty(p)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchOptionsProperty)); } else { return ast; } diff --git a/lib/creator/utils/is-assignment.js b/lib/creator/utils/is-assignment.js new file mode 100644 index 00000000000..08f6160b003 --- /dev/null +++ b/lib/creator/utils/is-assignment.js @@ -0,0 +1,5 @@ +module.exports = function(p, cb) { + if(p.parent.value.type === 'AssignmentExpression') { + return cb(p); + } +}; From 7e1ea073a93adebf8e14134abef65ece530aead8 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 14 Apr 2017 18:47:32 +0200 Subject: [PATCH 045/101] feat: find correct folder for packages --- lib/utils/resolve-packages.js | 8 ++++---- package.json | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/utils/resolve-packages.js b/lib/utils/resolve-packages.js index 7f4482a0452..738c294b45e 100644 --- a/lib/utils/resolve-packages.js +++ b/lib/utils/resolve-packages.js @@ -3,7 +3,7 @@ const fs = require('fs'); const chalk = require('chalk'); const spawn = require('cross-spawn'); const creator = require('../creator/index').creator; - +const globalPath = require('global-modules'); /* * @function processPromise * @@ -31,10 +31,10 @@ function processPromise(child) { function spawnChild(pkg) { // Different for windows, needs fix - if(fs.existsSync('/usr/local/lib/node_modules/' + pkg)) { - let removePath = '/usr/local/lib/node_modules/' + pkg; + let pkgPath = globalPath + '/' + pkg; + if(fs.existsSync(pkgPath)) { // HACK / FIXME -> npm update right away doesn't install the updated pkg. - spawn('rm', ['-rf', removePath], { stdio: 'inherit', customFds: [0, 1, 2] }); + spawn('rm', ['-rf', pkgPath], { stdio: 'inherit', customFds: [0, 1, 2] }); return spawn('npm', ['install', '-g', pkg], { stdio: 'inherit', customFds: [0, 1, 2] }); } else { return spawn('npm', ['install', '-g', pkg], { stdio: 'inherit', customFds: [0, 1, 2] }); diff --git a/package.json b/package.json index ffa07e19d9f..596931606ef 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "diff": "^3.2.0", "enhanced-resolve": "^3.0.2", "fit-commit-js": "^0.3.1", + "global-modules": "^0.2.3", "got": "^6.6.3", "inquirer": "^2.0.0", "interpret": "^1.0.1", From 4dbc02ab3b647fd3d620dc8e0413ff203f72b843 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 14 Apr 2017 19:12:23 +0200 Subject: [PATCH 046/101] fix: example transform in generator and fix to path --- lib/creator/transformations/module/module.js | 8 +- lib/creator/yeoman/webpack-generator.js | 111 +++++++++---------- lib/utils/resolve-packages.js | 4 +- 3 files changed, 63 insertions(+), 60 deletions(-) diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 4cc2556b1e8..6e69093eac9 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -89,12 +89,18 @@ module.exports = function(j, ast, yeomanConfig) { }); }); } else { + let pushProperty; + if(webpackProp === 'noParse') { + pushProperty = j.literal(webpackProperties.module[webpackProp]); + } else { + pushProperty = j.identifier(webpackProperties.module[webpackProp]); + } // module.rules is an external object prop.value.properties.push( j.property( 'init', j.identifier(webpackProp), - j.identifier(webpackProperties.module[webpackProp]) + pushProperty ) ); } diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 381bf8bb416..c177b9ed4d0 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -8,54 +8,56 @@ module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { super(args, opts); this.configuration = { - webpackOptions: {}, - topScope: [] + dev: { + webpackOptions: {}, + topScope: [] + } }; } prompting() { - this.configuration.webpackOptions.entry = { + this.configuration.dev.webpackOptions.entry = { vendor: 'home', js: 'yes', ohye: 'no' }; - this.configuration.webpackOptions.output = {}; - this.configuration.webpackOptions.output.filename = "'hello'"; - this.configuration.webpackOptions.output.path = 'path.join(__dirname, "somepath")'; - this.configuration.webpackOptions.output.pathinfo = true; - this.configuration.webpackOptions.output.publicPath = "'https://newbie.com'"; - this.configuration.webpackOptions.output.sourceMapFilename = "'[name].map'"; + this.configuration.dev.webpackOptions.output = {}; + this.configuration.dev.webpackOptions.output.filename = "'hello'"; + this.configuration.dev.webpackOptions.output.path = 'path.join(__dirname, "somepath")'; + this.configuration.dev.webpackOptions.output.pathinfo = true; + this.configuration.dev.webpackOptions.output.publicPath = "'https://newbie.com'"; + this.configuration.dev.webpackOptions.output.sourceMapFilename = "'[name].map'"; /* eslint-disable */ - this.configuration.webpackOptions.output.sourcePrefix = parseValue("'\t'") + this.configuration.dev.webpackOptions.output.sourcePrefix = parseValue("'\t'") /* esline-enable */ - this.configuration.webpackOptions.output.umdNamedDefine = true; - this.configuration.webpackOptions.output.strictModuleExceptionHandling = true; - this.configuration.webpackOptions.context = 'path.resolve(__dirname, "app")' - this.configuration.webpackOptions.resolve = {}; - this.configuration.webpackOptions.resolve.alias = {}; - this.configuration.webpackOptions.resolve.alias.hello = ':)' - this.configuration.webpackOptions.resolve.aliasFields = ["'browser'"] - this.configuration.webpackOptions.resolve.descriptionFiles = ["'a'", "'b'"] - this.configuration.webpackOptions.resolve.enforceExtension = false - this.configuration.webpackOptions.resolve.enforceModuleExtension = false - this.configuration.webpackOptions.resolve.extensions = ["'hey'", "'gi'"] - this.configuration.webpackOptions.resolve.mainFields = ["'mod'", "'ho'", "'bo'"] - this.configuration.webpackOptions.resolve.mainFiles = ["'index'"] - this.configuration.webpackOptions.resolve.modules = ["'Heo'"] - this.configuration.webpackOptions.resolve.unsafeCache = true; - this.configuration.webpackOptions.resolve.plugins = [ + this.configuration.dev.webpackOptions.output.umdNamedDefine = true; + this.configuration.dev.webpackOptions.output.strictModuleExceptionHandling = true; + this.configuration.dev.webpackOptions.context = 'path.resolve(__dirname, "app")' + this.configuration.dev.webpackOptions.resolve = {}; + this.configuration.dev.webpackOptions.resolve.alias = {}; + this.configuration.dev.webpackOptions.resolve.alias.hello = ':)' + this.configuration.dev.webpackOptions.resolve.aliasFields = ["'browser'"] + this.configuration.dev.webpackOptions.resolve.descriptionFiles = ["'a'", "'b'"] + this.configuration.dev.webpackOptions.resolve.enforceExtension = false + this.configuration.dev.webpackOptions.resolve.enforceModuleExtension = false + this.configuration.dev.webpackOptions.resolve.extensions = ["'hey'", "'gi'"] + this.configuration.dev.webpackOptions.resolve.mainFields = ["'mod'", "'ho'", "'bo'"] + this.configuration.dev.webpackOptions.resolve.mainFiles = ["'index'"] + this.configuration.dev.webpackOptions.resolve.modules = ["'Heo'"] + this.configuration.dev.webpackOptions.resolve.unsafeCache = true; + this.configuration.dev.webpackOptions.resolve.plugins = [ "new webpack.optimize.CommonsChunkPlugin({name:" + "'" + 'vendor' + "'" + ",filename:" + "'" + 'vendor' + "-[hash].min.js'})" ]; - this.configuration.webpackOptions.resolve.symlinks = true; - this.configuration.webpackOptions.resolve.cachePredicate = "function()" + "{\n return " + "true" + "\n}"; - this.configuration.webpackOptions.devtool = 'eval' - this.configuration.webpackOptions.target = 'async-node' - this.configuration.webpackOptions.watch = true; - this.configuration.webpackOptions.watchOptions = { + this.configuration.dev.webpackOptions.resolve.symlinks = true; + this.configuration.dev.webpackOptions.resolve.cachePredicate = "function()" + "{\n return " + "true" + "\n}"; + this.configuration.dev.webpackOptions.devtool = 'eval' + this.configuration.dev.webpackOptions.target = 'async-node' + this.configuration.dev.webpackOptions.watch = true; + this.configuration.dev.webpackOptions.watchOptions = { aggregateTimeout: 300, poll: 1000, ignored: '/node_modules/' } - this.configuration.webpackOptions.externals = { + this.configuration.dev.webpackOptions.externals = { jquery: 'jQuery', subtract: 'tracty', lodash : { @@ -64,11 +66,11 @@ module.exports = class WebpackGenerator extends Generator { root: '_' // indicates global variable } } - this.configuration.webpackOptions.externals = [ + this.configuration.dev.webpackOptions.externals = [ externalRegExpFunction('^.js$') ] - this.configuration.webpackOptions.externals = /^(jquery|\$)$/i - this.configuration.webpackOptions.node = { + this.configuration.dev.webpackOptions.externals = /^(jquery|\$)$/i + this.configuration.dev.webpackOptions.node = { console: false, global: true, process: true, @@ -77,22 +79,22 @@ module.exports = class WebpackGenerator extends Generator { __dirname: 'mock', setImmediate: true } - this.configuration.webpackOptions.performance = { + this.configuration.dev.webpackOptions.performance = { hints: "'warning'", maxEntrypointSize: 400000, maxAssetSize: 100000, assetFilter: assetFilterFunction('js') } - this.configuration.webpackOptions.stats = 'errors-only' - this.configuration.webpackOptions.amd = { + this.configuration.dev.webpackOptions.stats = 'errors-only' + this.configuration.dev.webpackOptions.amd = { jQuery: true, kQuery: false } - this.configuration.webpackOptions.bail = true; - this.configuration.webpackOptions.cache = parseValue('myCache') - this.configuration.webpackOptions.profile = true - this.configuration.webpackOptions.module = { - noParse: new RegExp('/jquery|lodash/'), + this.configuration.dev.webpackOptions.bail = true; + this.configuration.dev.webpackOptions.cache = 'myCache' + this.configuration.dev.webpackOptions.profile = true + this.configuration.dev.webpackOptions.module = { + noParse: new RegExp(/jquery|lodash/), rules: [ { test: new RegExp('/\.jsx?$/'), @@ -106,8 +108,8 @@ module.exports = class WebpackGenerator extends Generator { 'path.resolve(__dirname, ".." , "app", "demo-files")' /* eslint-enable */ ], - enforce: 'pre', - loader: 'babel-loader', + enforce: "'pre'", + loader: "'babel-loader'", options: { presets: ['es2015'] }, @@ -115,27 +117,22 @@ module.exports = class WebpackGenerator extends Generator { { test: new RegExp('\\.html$'), use: [ - 'htmllint-loader', + "'htmllint-loader'", { - loader: 'html-loader', + loader: "'html-loader'", options: { - hello: 'world' + hello: "'world'" } } ] }, - { oneOf: [] }, - { rules: [ ] }, - { resource: { and: [ ] } }, - { resource: { or: [ ] } }, - { resource: [ ] }, - { resource: { not: 'heo' } } ], } - this.configuration.webpackOptions.plugins = [ + this.configuration.dev.webpackOptions.plugins = [ "new webpack.optimize.CommonsChunkPlugin({name:" + "'" + 'vendor' + "'" + ",filename:" + "'" + 'vendor' + "-[hash].min.js'})" ] - this.configuration.topScope = ['const path = require("path");', 'const webpack = require("webpack");', 'const myCache = {};'] + this.configuration.dev.topScope = ['const path = require("path");', 'const webpack = require("webpack");', 'const myCache = {};'] + this.configuration.dev.configName = 'dev'; } }; diff --git a/lib/utils/resolve-packages.js b/lib/utils/resolve-packages.js index 738c294b45e..0f2a8c59e4e 100644 --- a/lib/utils/resolve-packages.js +++ b/lib/utils/resolve-packages.js @@ -31,7 +31,7 @@ function processPromise(child) { function spawnChild(pkg) { // Different for windows, needs fix - let pkgPath = globalPath + '/' + pkg; + const pkgPath = path.join(globalPath, '/', pkg); if(fs.existsSync(pkgPath)) { // HACK / FIXME -> npm update right away doesn't install the updated pkg. spawn('rm', ['-rf', pkgPath], { stdio: 'inherit', customFds: [0, 1, 2] }); @@ -60,7 +60,7 @@ module.exports = function resolvePackages(pkg) { processPromise(spawnChild(addon)).then( () => { try { // Different for windows, needs fix - packageLocations.push(path.join('/usr', 'local', 'lib', 'node_modules', addon)); + packageLocations.push(path.join(globalPath, '/', addon)); } catch(err) { console.log('Package wasn\'t validated correctly..'); console.log('Submit an issue for', pkg, 'if this persists'); From e315511c894cd3b6c6cdc9082912174abacaca22 Mon Sep 17 00:00:00 2001 From: Pavithra Kodmad Date: Sun, 16 Apr 2017 21:34:21 +0530 Subject: [PATCH 047/101] Add your first test (#114) --- .../entry/__snapshots__/entry.test.js.snap | 8 ++++++++ .../entry/__testfixtures__/entry-0.input.js | 1 + lib/creator/transformations/entry/entry.test.js | 3 +++ lib/transformations/defineTest.js | 11 ++++++++--- 4 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 lib/creator/transformations/entry/__snapshots__/entry.test.js.snap create mode 100644 lib/creator/transformations/entry/__testfixtures__/entry-0.input.js create mode 100644 lib/creator/transformations/entry/entry.test.js diff --git a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap new file mode 100644 index 00000000000..36bcb92718f --- /dev/null +++ b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap @@ -0,0 +1,8 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`entry transforms correctly using "entry-0" data 1`] = ` +"module.exports = { + entry: 'index.js' +} +" +`; diff --git a/lib/creator/transformations/entry/__testfixtures__/entry-0.input.js b/lib/creator/transformations/entry/__testfixtures__/entry-0.input.js new file mode 100644 index 00000000000..4ba52ba2c8d --- /dev/null +++ b/lib/creator/transformations/entry/__testfixtures__/entry-0.input.js @@ -0,0 +1 @@ +module.exports = {} diff --git a/lib/creator/transformations/entry/entry.test.js b/lib/creator/transformations/entry/entry.test.js new file mode 100644 index 00000000000..ec32b4c3f19 --- /dev/null +++ b/lib/creator/transformations/entry/entry.test.js @@ -0,0 +1,3 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'entry', 'entry-0', {entry: 'index.js'}); diff --git a/lib/transformations/defineTest.js b/lib/transformations/defineTest.js index 36a1017765e..06c16ed7e56 100644 --- a/lib/transformations/defineTest.js +++ b/lib/transformations/defineTest.js @@ -22,7 +22,7 @@ const path = require('path'); * - Test data should be located in a directory called __testfixtures__ * alongside the transform and __tests__ directory. */ -function runSingleTansform(dirName, transformName, testFilePrefix) { +function runSingleTansform(dirName, transformName, testFilePrefix, initOptions) { if (!testFilePrefix) { testFilePrefix = transformName; } @@ -42,6 +42,11 @@ function runSingleTansform(dirName, transformName, testFilePrefix) { jscodeshift = jscodeshift.withParser(module.parser); } const ast = jscodeshift(source); + if (initOptions) { + return transform(jscodeshift, ast, { + webpackOptions: initOptions + }).toSource({ quote: 'single' }); + } return transform(jscodeshift, ast, source).toSource({ quote: 'single' }); } @@ -49,13 +54,13 @@ function runSingleTansform(dirName, transformName, testFilePrefix) { * Handles some boilerplate around defining a simple jest/Jasmine test for a * jscodeshift transform. */ -function defineTest(dirName, transformName, testFilePrefix) { +function defineTest(dirName, transformName, testFilePrefix, type) { const testName = testFilePrefix ? `transforms correctly using "${testFilePrefix}" data` : 'transforms correctly'; describe(transformName, () => { it(testName, () => { - const output = runSingleTansform(dirName, transformName, testFilePrefix); + const output = runSingleTansform(dirName, transformName, testFilePrefix, type); expect(output).toMatchSnapshot(); }); }); From 4716da5fc14de5748a583fcb65b7b1ced37fa2a3 Mon Sep 17 00:00:00 2001 From: Pavithra Kodmad Date: Mon, 17 Apr 2017 12:27:53 +0530 Subject: [PATCH 048/101] Tests for entry.js (#115) * Add failing test * Pass the test on entry with array and update snapshots * If entry is an object * Add failing test case for externals * Fix bug with externals regexp --- .../entry/__snapshots__/entry.test.js.snap | 19 +++++++- lib/creator/transformations/entry/entry.js | 44 +++++++++++-------- .../transformations/entry/entry.test.js | 5 +++ .../__snapshots__/externals.test.js.snap | 13 ++++++ .../__testfixtures__/externals-0.input.js | 6 +++ .../transformations/externals/externals.js | 5 ++- .../externals/externals.test.js | 3 ++ 7 files changed, 73 insertions(+), 22 deletions(-) create mode 100644 lib/creator/transformations/externals/__snapshots__/externals.test.js.snap create mode 100644 lib/creator/transformations/externals/__testfixtures__/externals-0.input.js create mode 100644 lib/creator/transformations/externals/externals.test.js diff --git a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap index 36bcb92718f..edd5bfda37d 100644 --- a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap +++ b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap @@ -2,7 +2,24 @@ exports[`entry transforms correctly using "entry-0" data 1`] = ` "module.exports = { - entry: 'index.js' + 'entry': 'index.js' +} +" +`; + +exports[`entry transforms correctly using "entry-0" data 2`] = ` +"module.exports = { + 'entry': ['index.js', 'app.js'] +} +" +`; + +exports[`entry transforms correctly using "entry-0" data 3`] = ` +"module.exports = { + 'entry': { + 'index': 'index.js', + 'app': 'app.js' + } } " `; diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 4c59466077c..4e7d38c1f59 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,29 +1,35 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; + function addEntryPoints(entries) { + + if(Array.isArray(entries)) { + return j.arrayExpression(entries.map(entry => transformUtils.createLiteral(j, entry))); + } else if (typeof entries === 'string') { + return transformUtils.createLiteral(j, entries); + } + const entryKeys = Object.keys(entries); + if (entryKeys && entryKeys.length) { + return j.objectExpression( + entryKeys.map(entryKey => { + return j.property( 'init', + transformUtils.createLiteral(j, entryKey), + transformUtils.createLiteral(j, entries[entryKey]) + ); + }) + ); + } + + } function createEntryProperty(p) { let entryNode = p.value.properties; - entryNode.push(j.property('init', j.identifier('entry'), j.literal('null'))); - entryNode.filter(n => n.key.name === 'entry').forEach( (entryProp) => { - if(webpackProperties['entry'].length) { - entryProp.value.value = webpackProperties['entry']; - } - else { - entryProp.value.type = 'ObjectExpression'; - entryProp.value.properties = []; - Object.keys(webpackProperties['entry']).forEach( (webpackProps) => { - entryProp.value.properties.push( - j.property( - 'init', - j.identifier(webpackProps), - j.identifier(webpackProperties.entry[webpackProps]) - ) - ); - }); - } - }); + entryNode.push( + j.property( 'init', + transformUtils.createLiteral(j, 'entry'), + addEntryPoints(webpackProperties['entry']))); } if(webpackProperties['entry']) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/entry/entry.test.js b/lib/creator/transformations/entry/entry.test.js index ec32b4c3f19..8937db60cc2 100644 --- a/lib/creator/transformations/entry/entry.test.js +++ b/lib/creator/transformations/entry/entry.test.js @@ -1,3 +1,8 @@ const defineTest = require('../../../transformations/defineTest'); defineTest(__dirname, 'entry', 'entry-0', {entry: 'index.js'}); +defineTest(__dirname, 'entry', 'entry-0', {entry: ['index.js', 'app.js']}); +defineTest(__dirname, 'entry', 'entry-0', {entry: { + index: 'index.js', + app: 'app.js' +}}); diff --git a/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap b/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap new file mode 100644 index 00000000000..344c58e1a2e --- /dev/null +++ b/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap @@ -0,0 +1,13 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`externals transforms correctly using "externals-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + externals: /react/ +} +" +`; diff --git a/lib/creator/transformations/externals/__testfixtures__/externals-0.input.js b/lib/creator/transformations/externals/__testfixtures__/externals-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/externals/__testfixtures__/externals-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index e79f356d139..c8ec0f306f8 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; @@ -77,7 +77,8 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['externals'] && typeof webpackProperties['externals'] === 'object') { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createExternalProperty)); + .filter(p => transformUtils.safeTraverse(p , ['parent', 'value', 'left', 'property', 'name']) === 'exports') + .forEach(createExternalProperty); } else { return ast; } diff --git a/lib/creator/transformations/externals/externals.test.js b/lib/creator/transformations/externals/externals.test.js new file mode 100644 index 00000000000..85975ec1102 --- /dev/null +++ b/lib/creator/transformations/externals/externals.test.js @@ -0,0 +1,3 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'externals', 'externals-0', {externals : /react/}); From 1567daecc686a24136c156203c3c1bb6accafa2a Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 17 Apr 2017 14:52:34 +0200 Subject: [PATCH 049/101] fix: add identifier creation and fix entry tests --- .../entry/__snapshots__/entry.test.js.snap | 10 +++---- lib/creator/transformations/entry/entry.js | 10 +++---- .../transformations/entry/entry.test.js | 8 +++--- .../__snapshots__/utils.test.js.snap | 4 +++ lib/transformations/utils.js | 26 +++++++++++++++++++ lib/transformations/utils.test.js | 12 +++++++++ 6 files changed, 56 insertions(+), 14 deletions(-) diff --git a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap index edd5bfda37d..76ee2c05268 100644 --- a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap +++ b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap @@ -2,23 +2,23 @@ exports[`entry transforms correctly using "entry-0" data 1`] = ` "module.exports = { - 'entry': 'index.js' + entry: 'index.js' } " `; exports[`entry transforms correctly using "entry-0" data 2`] = ` "module.exports = { - 'entry': ['index.js', 'app.js'] + entry: ['index.js', 'app.js'] } " `; exports[`entry transforms correctly using "entry-0" data 3`] = ` "module.exports = { - 'entry': { - 'index': 'index.js', - 'app': 'app.js' + entry: { + index: 'index.js', + app: 'app.js' } } " diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 4e7d38c1f59..bc95f986cf0 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -7,17 +7,17 @@ module.exports = function(j, ast, yeomanConfig) { function addEntryPoints(entries) { if(Array.isArray(entries)) { - return j.arrayExpression(entries.map(entry => transformUtils.createLiteral(j, entry))); + return j.arrayExpression(entries.map(entry => transformUtils.createIdentifierOrLiteral(j, entry))); } else if (typeof entries === 'string') { - return transformUtils.createLiteral(j, entries); + return transformUtils.createIdentifierOrLiteral(j, entries); } const entryKeys = Object.keys(entries); if (entryKeys && entryKeys.length) { return j.objectExpression( entryKeys.map(entryKey => { return j.property( 'init', - transformUtils.createLiteral(j, entryKey), - transformUtils.createLiteral(j, entries[entryKey]) + transformUtils.createIdentifierOrLiteral(j, entryKey), + transformUtils.createIdentifierOrLiteral(j, entries[entryKey]) ); }) ); @@ -28,7 +28,7 @@ module.exports = function(j, ast, yeomanConfig) { let entryNode = p.value.properties; entryNode.push( j.property( 'init', - transformUtils.createLiteral(j, 'entry'), + transformUtils.createIdentifierOrLiteral(j, 'entry'), addEntryPoints(webpackProperties['entry']))); } if(webpackProperties['entry']) { diff --git a/lib/creator/transformations/entry/entry.test.js b/lib/creator/transformations/entry/entry.test.js index 8937db60cc2..ace89d6c8ee 100644 --- a/lib/creator/transformations/entry/entry.test.js +++ b/lib/creator/transformations/entry/entry.test.js @@ -1,8 +1,8 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'entry', 'entry-0', {entry: 'index.js'}); -defineTest(__dirname, 'entry', 'entry-0', {entry: ['index.js', 'app.js']}); +defineTest(__dirname, 'entry', 'entry-0', {entry: '\'index.js\''}); +defineTest(__dirname, 'entry', 'entry-0', {entry: ['\'index.js\'', '\'app.js\'']}); defineTest(__dirname, 'entry', 'entry-0', {entry: { - index: 'index.js', - app: 'app.js' + index: '\'index.js\'', + app: '\'app.js\'' }}); diff --git a/lib/transformations/__snapshots__/utils.test.js.snap b/lib/transformations/__snapshots__/utils.test.js.snap index 7a30f2983a4..ac742027a35 100644 --- a/lib/transformations/__snapshots__/utils.test.js.snap +++ b/lib/transformations/__snapshots__/utils.test.js.snap @@ -1,5 +1,9 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`utils createIdentifierOrLiteral should create basic literal 1`] = `"'stringLiteral'"`; + +exports[`utils createIdentifierOrLiteral should create boolean 1`] = `"true"`; + exports[`utils createLiteral should create basic literal 1`] = `"\\"stringLiteral\\""`; exports[`utils createLiteral should create boolean 1`] = `"true"`; diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index 428d0e315ee..cccfff5d57f 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -111,6 +111,31 @@ function createLiteral(j, val) { return j.literal(literalVal); } +/* + * @function createIdentifierOrLiteral + * + * Creates an appropriate identifier or literal property + * + * @param j — jscodeshift API + * @param { string | boolean | number } val + * @returns { Node } + * */ + +function createIdentifierOrLiteral(j, val) { + let literalVal = val; + // We'll need String to native type conversions + if (typeof val === 'string') { + // 'true' => true + if (val === 'true') literalVal = true; + // 'false' => false + if (val === 'false') literalVal = false; + // '1' => 1 + if (!isNaN(Number(val))) literalVal = Number(val); + // Use identifier instead + else return j.identifier(literalVal); + } + return j.literal(literalVal); +} /* * @function createOrUpdatePluginByName * @@ -255,6 +280,7 @@ module.exports = { findVariableToPlugin, isType, createLiteral, + createIdentifierOrLiteral, findObjWithOneOfKeys, getRequire }; diff --git a/lib/transformations/utils.test.js b/lib/transformations/utils.test.js index 73a8c93a9fc..c98d9444a0a 100644 --- a/lib/transformations/utils.test.js +++ b/lib/transformations/utils.test.js @@ -143,6 +143,18 @@ var a = { plugs: [] } const literal = utils.createLiteral(j, 'true'); expect(j(literal).toSource()).toMatchSnapshot(); }); + + }); + + describe('createIdentifierOrLiteral', () => { + it('should create basic literal', () => { + const literal = utils.createIdentifierOrLiteral(j, '\'stringLiteral\''); + expect(j(literal).toSource()).toMatchSnapshot(); + }); + it('should create boolean', () => { + const literal = utils.createLiteral(j, 'true'); + expect(j(literal).toSource()).toMatchSnapshot(); + }); }); describe('findObjWithOneOfKeys', () => { From c052bc879680a56116a855f4ef87bea424ebf518 Mon Sep 17 00:00:00 2001 From: Pavithra Kodmad Date: Tue, 18 Apr 2017 15:20:33 +0530 Subject: [PATCH 050/101] Add more tests (#116) * Test watch transform * Test watch transform (Doesnt look for existing obj) * Test target transform (Doesnt look for existing obj) * Test plugins transform (Doesnt look for existing obj) * Add failing test case for node * Add test case for node * Add first instance of duplicate check and override * Extract a function * Make a util to override object params --- .../node/__snapshots__/node.test.js.snap | 21 ++++++ .../node/__testfixtures__/node-0.input.js | 6 ++ lib/creator/transformations/node/node.test.js | 11 ++++ .../__snapshots__/plugins.test.js.snap | 15 +++++ .../__testfixtures__/plugins-0.input.js | 6 ++ .../transformations/plugins/plugins.test.js | 5 ++ .../target/__snapshots__/target.test.js.snap | 26 ++++++++ .../target/__testfixtures__/target-0.input.js | 6 ++ .../target/__testfixtures__/target-1.input.js | 7 ++ .../transformations/target/target.test.js | 4 ++ .../watch/__snapshots__/watch.test.js.snap | 49 ++++++++++++++ .../__snapshots__/watchOptions.test.js.snap | 64 +++++++++++++++++++ .../watch/__testfixtures__/watch-0.input.js | 6 ++ .../watch/__testfixtures__/watch-1.input.js | 8 +++ .../watch/__testfixtures__/watch-2.input.js | 10 +++ lib/creator/transformations/watch/watch.js | 8 ++- .../transformations/watch/watch.test.js | 6 ++ .../watch/watchOptions.test.js | 19 ++++++ .../__snapshots__/utils.test.js.snap | 17 +++++ lib/transformations/utils.js | 26 +++++++- lib/transformations/utils.test.js | 21 ++++++ 21 files changed, 337 insertions(+), 4 deletions(-) create mode 100644 lib/creator/transformations/node/__snapshots__/node.test.js.snap create mode 100644 lib/creator/transformations/node/__testfixtures__/node-0.input.js create mode 100644 lib/creator/transformations/node/node.test.js create mode 100644 lib/creator/transformations/plugins/__snapshots__/plugins.test.js.snap create mode 100644 lib/creator/transformations/plugins/__testfixtures__/plugins-0.input.js create mode 100644 lib/creator/transformations/plugins/plugins.test.js create mode 100644 lib/creator/transformations/target/__snapshots__/target.test.js.snap create mode 100644 lib/creator/transformations/target/__testfixtures__/target-0.input.js create mode 100644 lib/creator/transformations/target/__testfixtures__/target-1.input.js create mode 100644 lib/creator/transformations/target/target.test.js create mode 100644 lib/creator/transformations/watch/__snapshots__/watch.test.js.snap create mode 100644 lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap create mode 100644 lib/creator/transformations/watch/__testfixtures__/watch-0.input.js create mode 100644 lib/creator/transformations/watch/__testfixtures__/watch-1.input.js create mode 100644 lib/creator/transformations/watch/__testfixtures__/watch-2.input.js create mode 100644 lib/creator/transformations/watch/watch.test.js create mode 100644 lib/creator/transformations/watch/watchOptions.test.js diff --git a/lib/creator/transformations/node/__snapshots__/node.test.js.snap b/lib/creator/transformations/node/__snapshots__/node.test.js.snap new file mode 100644 index 00000000000..0046bc33d63 --- /dev/null +++ b/lib/creator/transformations/node/__snapshots__/node.test.js.snap @@ -0,0 +1,21 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`node transforms correctly using "node-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + node: { + console: false, + global: true, + process: true, + Buffer: true, + __filename: mock, + __dirname: mock, + setImmediate: true + } +} +" +`; diff --git a/lib/creator/transformations/node/__testfixtures__/node-0.input.js b/lib/creator/transformations/node/__testfixtures__/node-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/node/__testfixtures__/node-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/node/node.test.js b/lib/creator/transformations/node/node.test.js new file mode 100644 index 00000000000..bd1b0e0484b --- /dev/null +++ b/lib/creator/transformations/node/node.test.js @@ -0,0 +1,11 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'node', 'node-0', {node : { + console: false, + global: true, + process: true, + Buffer: true, + __filename: 'mock', + __dirname: 'mock', + setImmediate: true +}}); diff --git a/lib/creator/transformations/plugins/__snapshots__/plugins.test.js.snap b/lib/creator/transformations/plugins/__snapshots__/plugins.test.js.snap new file mode 100644 index 00000000000..6fbe0c9fe35 --- /dev/null +++ b/lib/creator/transformations/plugins/__snapshots__/plugins.test.js.snap @@ -0,0 +1,15 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`plugins transforms correctly using "plugins-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + plugins: [ + new webpack.optimize.CommonsChunkPlugin({name:'vendor',filename:'vendor-[hash].min.js'}) + ] +} +" +`; diff --git a/lib/creator/transformations/plugins/__testfixtures__/plugins-0.input.js b/lib/creator/transformations/plugins/__testfixtures__/plugins-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/plugins/__testfixtures__/plugins-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/plugins/plugins.test.js b/lib/creator/transformations/plugins/plugins.test.js new file mode 100644 index 00000000000..5825f2a52dd --- /dev/null +++ b/lib/creator/transformations/plugins/plugins.test.js @@ -0,0 +1,5 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'plugins', 'plugins-0', {plugins : [ + 'new webpack.optimize.CommonsChunkPlugin({name:' + '\'' + 'vendor' + '\'' + ',filename:' + '\'' + 'vendor' + '-[hash].min.js\'})' +]}); diff --git a/lib/creator/transformations/target/__snapshots__/target.test.js.snap b/lib/creator/transformations/target/__snapshots__/target.test.js.snap new file mode 100644 index 00000000000..663e3b899af --- /dev/null +++ b/lib/creator/transformations/target/__snapshots__/target.test.js.snap @@ -0,0 +1,26 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`target transforms correctly using "target-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + target: async-node +} +" +`; + +exports[`target transforms correctly using "target-1" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + target: 'node', + target: async-node +} +" +`; diff --git a/lib/creator/transformations/target/__testfixtures__/target-0.input.js b/lib/creator/transformations/target/__testfixtures__/target-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/target/__testfixtures__/target-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/target/__testfixtures__/target-1.input.js b/lib/creator/transformations/target/__testfixtures__/target-1.input.js new file mode 100644 index 00000000000..c8e83f95936 --- /dev/null +++ b/lib/creator/transformations/target/__testfixtures__/target-1.input.js @@ -0,0 +1,7 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + target: 'node' +} diff --git a/lib/creator/transformations/target/target.test.js b/lib/creator/transformations/target/target.test.js new file mode 100644 index 00000000000..f8760bb98dd --- /dev/null +++ b/lib/creator/transformations/target/target.test.js @@ -0,0 +1,4 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'target', 'target-0', {target : 'async-node'}); +defineTest(__dirname, 'target', 'target-1', {target : 'async-node'}); diff --git a/lib/creator/transformations/watch/__snapshots__/watch.test.js.snap b/lib/creator/transformations/watch/__snapshots__/watch.test.js.snap new file mode 100644 index 00000000000..70131f1c10c --- /dev/null +++ b/lib/creator/transformations/watch/__snapshots__/watch.test.js.snap @@ -0,0 +1,49 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`watch transforms correctly using "watch-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + watch: true +} +" +`; + +exports[`watch transforms correctly using "watch-0" data 2`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + watch: false +} +" +`; + +exports[`watch transforms correctly using "watch-1" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + watch: true, + watchOptions: {} +} +" +`; + +exports[`watch transforms correctly using "watch-1" data 2`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + watch: false, + watchOptions: {} +} +" +`; diff --git a/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap b/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap new file mode 100644 index 00000000000..9f9b0088461 --- /dev/null +++ b/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap @@ -0,0 +1,64 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`watchOptions transforms correctly using "watch-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + watchOptions: { + aggregateTimeout: 300, + poll: 1000, + ignored: /node_modules/ + } +} +" +`; + +exports[`watchOptions transforms correctly using "watch-1" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + watch: false, + watchOptions: { + aggregateTimeout: 300, + poll: 1000, + ignored: /node_modules/ + }, + + watchOptions: { + aggregateTimeout: 300, + poll: 1000, + ignored: /node_modules/ + } +} +" +`; + +exports[`watchOptions transforms correctly using "watch-2" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + watch: false, + watchOptions: { + aggregateTimeout: 320, + aggregateTimeout: 300, + poll: 1000, + ignored: /node_modules/ + }, + + watchOptions: { + aggregateTimeout: 300, + poll: 1000, + ignored: /node_modules/ + } +} +" +`; diff --git a/lib/creator/transformations/watch/__testfixtures__/watch-0.input.js b/lib/creator/transformations/watch/__testfixtures__/watch-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/watch/__testfixtures__/watch-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/watch/__testfixtures__/watch-1.input.js b/lib/creator/transformations/watch/__testfixtures__/watch-1.input.js new file mode 100644 index 00000000000..503bb1d4a71 --- /dev/null +++ b/lib/creator/transformations/watch/__testfixtures__/watch-1.input.js @@ -0,0 +1,8 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + watch: false, + watchOptions: {} +} diff --git a/lib/creator/transformations/watch/__testfixtures__/watch-2.input.js b/lib/creator/transformations/watch/__testfixtures__/watch-2.input.js new file mode 100644 index 00000000000..1d94f02f15f --- /dev/null +++ b/lib/creator/transformations/watch/__testfixtures__/watch-2.input.js @@ -0,0 +1,10 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + watch: false, + watchOptions: { + aggregateTimeout: 320 + } +} diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 2e23c0c2616..188b34f59cf 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,11 +1,11 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchProperty(p) { - return p.value.properties.push( - j.property('init', j.identifier('watch'), j.literal(webpackProperties['watch'])) - ); + const propValue = transformUtils.createIdentifierOrLiteral(j, webpackProperties['watch']); + transformUtils.checkIfExistsAndAddValue(j, p, 'watch', propValue); } if(typeof(webpackProperties['watch']) === 'boolean') { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchProperty)); @@ -13,3 +13,5 @@ module.exports = function(j, ast, yeomanConfig) { return ast; } }; + + diff --git a/lib/creator/transformations/watch/watch.test.js b/lib/creator/transformations/watch/watch.test.js new file mode 100644 index 00000000000..1b5e1e195c3 --- /dev/null +++ b/lib/creator/transformations/watch/watch.test.js @@ -0,0 +1,6 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'watch', 'watch-0', {watch : true}); +defineTest(__dirname, 'watch', 'watch-0', {watch : false}); +defineTest(__dirname, 'watch', 'watch-1', {watch : true}); +defineTest(__dirname, 'watch', 'watch-1', {watch : false}); diff --git a/lib/creator/transformations/watch/watchOptions.test.js b/lib/creator/transformations/watch/watchOptions.test.js new file mode 100644 index 00000000000..c457bfbb388 --- /dev/null +++ b/lib/creator/transformations/watch/watchOptions.test.js @@ -0,0 +1,19 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'watchOptions', 'watch-0', {watchOptions : { + aggregateTimeout: 300, + poll: 1000, + ignored: '/node_modules/' +}}); + +defineTest(__dirname, 'watchOptions', 'watch-1', {watchOptions : { + aggregateTimeout: 300, + poll: 1000, + ignored: '/node_modules/' +}}); + +defineTest(__dirname, 'watchOptions', 'watch-2', {watchOptions : { + aggregateTimeout: 300, + poll: 1000, + ignored: '/node_modules/' +}}); diff --git a/lib/transformations/__snapshots__/utils.test.js.snap b/lib/transformations/__snapshots__/utils.test.js.snap index ac742027a35..400542763b9 100644 --- a/lib/transformations/__snapshots__/utils.test.js.snap +++ b/lib/transformations/__snapshots__/utils.test.js.snap @@ -1,5 +1,22 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`utils checkIfExistsAndAddValue should create new prop if none exist 1`] = ` +" + module.exports = { + entry: 'index.js', + externals: \\"React\\" + } + " +`; + +exports[`utils checkIfExistsAndAddValue should override prop if it exists 1`] = ` +" + module.exports = { + entry: \\"app.js\\" + } + " +`; + exports[`utils createIdentifierOrLiteral should create basic literal 1`] = `"'stringLiteral'"`; exports[`utils createIdentifierOrLiteral should create boolean 1`] = `"true"`; diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index cccfff5d57f..46b21c788ab 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -271,6 +271,29 @@ function getRequire(j, constName, packagePath) { ]); } +/* +* @function checkIfExistsAndAddValue +* +* If a prop exists, it overrides it, else it creates a new one +* @param j — jscodeshift API +* @param { Node } node - objectexpression to check +* @param { string } key - Key of the property +* @param { string } value - computed value of the property +* @returns - nothing +*/ + +function checkIfExistsAndAddValue(j, node, key, value) { + const existingProp = node.value.properties.filter(prop => prop.key.name === key); + let prop; + if (existingProp.length > 0){ + prop = existingProp[0]; + prop.value = value; + } else { + prop = j.property('init', j.identifier(key), value); + node.value.properties.push(prop); + } +} + module.exports = { safeTraverse, createProperty, @@ -282,5 +305,6 @@ module.exports = { createLiteral, createIdentifierOrLiteral, findObjWithOneOfKeys, - getRequire + getRequire, + checkIfExistsAndAddValue }; diff --git a/lib/transformations/utils.test.js b/lib/transformations/utils.test.js index c98d9444a0a..7b0b3d8bdfd 100644 --- a/lib/transformations/utils.test.js +++ b/lib/transformations/utils.test.js @@ -176,4 +176,25 @@ var a = { plugs: [] } expect(j(require).toSource()).toMatchSnapshot(); }); }); + + describe('checkIfExistsAndAddValue', () => { + it('should create new prop if none exist', () => { + const ast = j(` + module.exports = { + entry: 'index.js' + } + `); + ast.find(j.ObjectExpression).forEach(node => utils.checkIfExistsAndAddValue(j, node, 'externals', j.literal('React'))); + expect(ast.toSource()).toMatchSnapshot(); + }); + it('should override prop if it exists', () => { + const ast = j(` + module.exports = { + entry: 'index.js' + } + `); + ast.find(j.ObjectExpression).forEach(node => utils.checkIfExistsAndAddValue(j, node, 'entry', j.literal('app.js'))); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); }); From b88e3df16d60b6ad98381f4967904542eb2f78e4 Mon Sep 17 00:00:00 2001 From: Pavithra Kodmad Date: Tue, 18 Apr 2017 18:27:11 +0530 Subject: [PATCH 051/101] Cleanup the ast branch transformation (#117) * refactor watch options * refactor target * refactor context * refactor devtool * refactor node * refactor plugins * refactor amd * refactor bail * Moar tests --- .../__snapshots__/context.test.js.snap | 24 +++++++++ .../__testfixtures__/context-0.input.js | 6 +++ .../__testfixtures__/context-1.input.js | 7 +++ .../transformations/context/context.js | 7 +-- .../transformations/context/context.test.js | 4 ++ .../__snapshots__/devtool.test.js.snap | 24 +++++++++ .../__testfixtures__/devtools-0.input.js | 6 +++ .../__testfixtures__/devtools-1.input.js | 7 +++ .../transformations/devtool/devtool.js | 8 ++- .../transformations/devtool/devtool.test.js | 4 ++ lib/creator/transformations/node/node.js | 33 ++++-------- .../other/__snapshots__/others.test.js.snap | 52 +++++++++++++++++++ .../other/__testfixtures__/others-0.input.js | 6 +++ lib/creator/transformations/other/amd.js | 33 ++++-------- lib/creator/transformations/other/bail.js | 6 +-- lib/creator/transformations/other/cache.js | 12 ++--- .../transformations/other/others.test.js | 9 ++++ lib/creator/transformations/other/profile.js | 12 ++--- .../transformations/plugins/plugins.js | 15 +++--- .../target/__snapshots__/target.test.js.snap | 8 ++- lib/creator/transformations/target/target.js | 6 +-- .../__snapshots__/watchOptions.test.js.snap | 31 +++-------- .../transformations/watch/watchOptions.js | 36 ++++--------- 23 files changed, 217 insertions(+), 139 deletions(-) create mode 100644 lib/creator/transformations/context/__snapshots__/context.test.js.snap create mode 100644 lib/creator/transformations/context/__testfixtures__/context-0.input.js create mode 100644 lib/creator/transformations/context/__testfixtures__/context-1.input.js create mode 100644 lib/creator/transformations/context/context.test.js create mode 100644 lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap create mode 100644 lib/creator/transformations/devtool/__testfixtures__/devtools-0.input.js create mode 100644 lib/creator/transformations/devtool/__testfixtures__/devtools-1.input.js create mode 100644 lib/creator/transformations/devtool/devtool.test.js create mode 100644 lib/creator/transformations/other/__snapshots__/others.test.js.snap create mode 100644 lib/creator/transformations/other/__testfixtures__/others-0.input.js create mode 100644 lib/creator/transformations/other/others.test.js diff --git a/lib/creator/transformations/context/__snapshots__/context.test.js.snap b/lib/creator/transformations/context/__snapshots__/context.test.js.snap new file mode 100644 index 00000000000..40b90bf1348 --- /dev/null +++ b/lib/creator/transformations/context/__snapshots__/context.test.js.snap @@ -0,0 +1,24 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`context transforms correctly using "context-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + context: path.resolve(__dirname, \\"app\\") +} +" +`; + +exports[`context transforms correctly using "context-1" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + context: path.resolve(__dirname, \\"app\\") +} +" +`; diff --git a/lib/creator/transformations/context/__testfixtures__/context-0.input.js b/lib/creator/transformations/context/__testfixtures__/context-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/context/__testfixtures__/context-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/context/__testfixtures__/context-1.input.js b/lib/creator/transformations/context/__testfixtures__/context-1.input.js new file mode 100644 index 00000000000..21e6a8a9e4c --- /dev/null +++ b/lib/creator/transformations/context/__testfixtures__/context-1.input.js @@ -0,0 +1,7 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + context: 'blah' +} diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 5036fa4c2f2..a5b64c1d505 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,11 +1,12 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createContextProperty(p) { - return p.value.properties.push( - j.property('init', j.identifier('context'), j.identifier(webpackProperties['context'])) - ); + const propValue = transformUtils.createIdentifierOrLiteral(j, webpackProperties['context']); + transformUtils.checkIfExistsAndAddValue(j, p, 'context', propValue); } if(webpackProperties['context'] && webpackProperties['context'].length) { diff --git a/lib/creator/transformations/context/context.test.js b/lib/creator/transformations/context/context.test.js new file mode 100644 index 00000000000..5179fd44201 --- /dev/null +++ b/lib/creator/transformations/context/context.test.js @@ -0,0 +1,4 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'context', 'context-0', {context : 'path.resolve(__dirname, "app")'}); +defineTest(__dirname, 'context', 'context-1', {context : 'path.resolve(__dirname, "app")'}); diff --git a/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap new file mode 100644 index 00000000000..1915162eb06 --- /dev/null +++ b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap @@ -0,0 +1,24 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`devtool transforms correctly using "devtools-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + devtools: 'source-map' +} +" +`; + +exports[`devtool transforms correctly using "devtools-1" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + devtools: 'source-map' +} +" +`; diff --git a/lib/creator/transformations/devtool/__testfixtures__/devtools-0.input.js b/lib/creator/transformations/devtool/__testfixtures__/devtools-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/devtool/__testfixtures__/devtools-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/devtool/__testfixtures__/devtools-1.input.js b/lib/creator/transformations/devtool/__testfixtures__/devtools-1.input.js new file mode 100644 index 00000000000..4d2b2302b9b --- /dev/null +++ b/lib/creator/transformations/devtool/__testfixtures__/devtools-1.input.js @@ -0,0 +1,7 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + devtools: 'eval' +} diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index a0903e0f724..f8dc86b7f16 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,14 +1,12 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createDevToolProperty(p) { - return p.value.properties.push( - j.property('init', - j.identifier('devtool'), - j.identifier(webpackProperties['devtool'])) - ); + const propValue = j.literal(webpackProperties['devtool']); + transformUtils.checkIfExistsAndAddValue(j, p, 'devtools', propValue); } if(webpackProperties['devtool'] && webpackProperties['devtool'].length) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/devtool/devtool.test.js b/lib/creator/transformations/devtool/devtool.test.js new file mode 100644 index 00000000000..45d21618e87 --- /dev/null +++ b/lib/creator/transformations/devtool/devtool.test.js @@ -0,0 +1,4 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'devtool', 'devtools-0', {devtool : 'source-map'}); +defineTest(__dirname, 'devtool', 'devtools-1', {devtool : 'source-map'}); diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index 53fb84a15e1..bdc7bff0f75 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -1,32 +1,17 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createNodeProperty(p) { - let node = p.value.properties; - node.push(j.property('init', j.identifier('node'), j.objectExpression([]))); - node.filter(n => n.key.name === 'node').forEach( (prop) => { - Object.keys(webpackProperties.node).forEach( (webpackProp) => { - if(typeof(webpackProperties.node[webpackProp]) === 'boolean') { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.literal(webpackProperties.node[webpackProp]) - ) - ); - } else { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.identifier(webpackProperties.node[webpackProp] - ) - ) - ); - } - }); - }); + const nodeVal = webpackProperties['node']; + const propVal = j.objectExpression( + Object.keys(nodeVal).map(prop => { + return j.property('init', j.identifier(prop), + transformUtils.createIdentifierOrLiteral(j, nodeVal[prop])); + }) + ); + transformUtils.checkIfExistsAndAddValue(j, p, 'node', propVal); } if(webpackProperties['node'] && typeof(webpackProperties['node']) === 'object') { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/other/__snapshots__/others.test.js.snap b/lib/creator/transformations/other/__snapshots__/others.test.js.snap new file mode 100644 index 00000000000..5b2dcaf01df --- /dev/null +++ b/lib/creator/transformations/other/__snapshots__/others.test.js.snap @@ -0,0 +1,52 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`amd transforms correctly using "others-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + amd: { + jQuery: true, + kQuery: false + } +} +" +`; + +exports[`bail transforms correctly using "others-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + bail: true +} +" +`; + +exports[`cache transforms correctly using "others-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + cache: true +} +" +`; + +exports[`profile transforms correctly using "others-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + profile: true +} +" +`; diff --git a/lib/creator/transformations/other/__testfixtures__/others-0.input.js b/lib/creator/transformations/other/__testfixtures__/others-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/other/__testfixtures__/others-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index 1f71e252b57..91f8f430d80 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -1,31 +1,18 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createAMDProperty(p) { - let amdNode = p.value.properties; - amdNode.push(j.property('init', j.identifier('amd'), j.objectExpression([]))); - amdNode.filter(n => n.key.name === 'amd').forEach( (prop) => { - Object.keys(webpackProperties['amd']).forEach( (webpackProp) => { - if(typeof(webpackProperties.amd[webpackProp]) === 'boolean') { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.literal(webpackProperties.amd[webpackProp]) - ) - ); - } else { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.identifier(webpackProperties.amd[webpackProp]) - ) - ); - } - }); - }); + const amd = webpackProperties['amd']; + const propVal = j.objectExpression( + Object.keys(amd).map(prop => { + return j.property('init', j.identifier(prop), + transformUtils.createIdentifierOrLiteral(j, amd[prop]) + ); + }) + ); + transformUtils.checkIfExistsAndAddValue(j, p, 'amd', propVal); } if(webpackProperties['amd'] && typeof(webpackProperties['amd']) === 'object') { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index ce65568a827..d7c72dc025c 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,12 +1,12 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createBailProperty(p) { - let bailVal = (typeof webpackProperties['bail'] === 'boolean') ? - j.literal(webpackProperties['bail']) : j.identifier(webpackProperties['bail']); - p.value.properties.push(j.property('init', j.identifier('bail'), bailVal)); + let propVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['bail']); + transformUtils.checkIfExistsAndAddValue(j, p, 'bail', propVal); } if(webpackProperties['bail']) { diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index d939bdfe95c..4a3b6ed0d15 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,17 +1,11 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createCacheProperty(p) { - if(typeof(webpackProperties['cache']) === 'object') { - return p.value.properties.push( - j.property('init', j.identifier('cache'), j.identifier(webpackProperties['cache'])) - ); - } else { - p.value.properties.push( - j.property('init', j.identifier('cache'), j.literal(webpackProperties['cache'])) - ); - } + let propVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['cache']); + transformUtils.checkIfExistsAndAddValue(j, p, 'cache', propVal); } if(webpackProperties['cache']) { diff --git a/lib/creator/transformations/other/others.test.js b/lib/creator/transformations/other/others.test.js new file mode 100644 index 00000000000..53326e09002 --- /dev/null +++ b/lib/creator/transformations/other/others.test.js @@ -0,0 +1,9 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'amd', 'others-0', {amd : { + jQuery: true, + kQuery: false} +}); +defineTest(__dirname, 'bail', 'others-0', {bail : true}); +defineTest(__dirname, 'cache', 'others-0', {cache : true}); +defineTest(__dirname, 'profile', 'others-0', {profile : true}); diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index 52dca089230..abb362e0b3a 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,17 +1,11 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createProfileProperty(p) { - if(typeof(webpackProperties['profile']) === 'boolean') { - return p.value.properties.push( - j.property('init', j.identifier('profile'), j.literal(webpackProperties['profile'])) - ); - } else { - return p.value.properties.push( - j.property('init', j.identifier('profile'), j.identifier(webpackProperties['profile'])) - ); - } + let propVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['profile']); + transformUtils.checkIfExistsAndAddValue(j, p, 'profile', propVal); } if(webpackProperties['profile']) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index 6d0fb89cfef..60926d2b653 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -1,15 +1,16 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createPluginsProperty(p) { - const pluginArray = j.property('init', j.identifier('plugins'), j.arrayExpression([])); - Object.keys(webpackProperties.plugins).forEach( (plugin) => { - if(webpackProperties.plugins[plugin]) { - pluginArray.value.elements.push(j.identifier(webpackProperties.plugins[plugin])); - } - }); - return p.value.properties.push(pluginArray); + const plugins = webpackProperties['plugins']; + const propVal = j.arrayExpression( + Object.keys(plugins).map(plugin => { + return j.identifier(plugins[plugin]); + }) + ); + transformUtils.checkIfExistsAndAddValue(j, p, 'plugins', propVal); } if(webpackProperties['plugins'] && Array.isArray(webpackProperties['plugins'])) { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createPluginsProperty)); diff --git a/lib/creator/transformations/target/__snapshots__/target.test.js.snap b/lib/creator/transformations/target/__snapshots__/target.test.js.snap index 663e3b899af..63d87b56960 100644 --- a/lib/creator/transformations/target/__snapshots__/target.test.js.snap +++ b/lib/creator/transformations/target/__snapshots__/target.test.js.snap @@ -14,13 +14,11 @@ exports[`target transforms correctly using "target-0" data 1`] = ` exports[`target transforms correctly using "target-1" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - - target: 'node', - target: async-node + target: async-node } " `; diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 1a9d0da2c98..ef4b5393768 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,11 +1,11 @@ const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createTargetProperty(p) { - return p.value.properties.push( - j.property('init', j.identifier('target'), j.identifier(webpackProperties['target'])) - ); + const propValue = transformUtils.createIdentifierOrLiteral(j, webpackProperties['target']); + transformUtils.checkIfExistsAndAddValue(j, p, 'target', propValue); } if(webpackProperties['target'] && webpackProperties['target'].length) { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createTargetProperty)); diff --git a/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap b/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap index 9f9b0088461..cf7976733c0 100644 --- a/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap +++ b/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap @@ -18,19 +18,12 @@ exports[`watchOptions transforms correctly using "watch-0" data 1`] = ` exports[`watchOptions transforms correctly using "watch-1" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - - watch: false, - watchOptions: { - aggregateTimeout: 300, - poll: 1000, - ignored: /node_modules/ - }, - - watchOptions: { + watch: false, + watchOptions: { aggregateTimeout: 300, poll: 1000, ignored: /node_modules/ @@ -41,20 +34,12 @@ exports[`watchOptions transforms correctly using "watch-1" data 1`] = ` exports[`watchOptions transforms correctly using "watch-2" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - - watch: false, - watchOptions: { - aggregateTimeout: 320, - aggregateTimeout: 300, - poll: 1000, - ignored: /node_modules/ - }, - - watchOptions: { + watch: false, + watchOptions: { aggregateTimeout: 300, poll: 1000, ignored: /node_modules/ diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index 6d2bc984410..8f9ee9331ee 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -1,36 +1,22 @@ const watchOptionTypes = require('./watchOptions-types'); const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchOptionsProperty(p) { - let watchOptionsNode = p.value.properties; - watchOptionsNode.push(j.property('init', j.identifier('watchOptions'), j.objectExpression([]))); - watchOptionsNode.filter(n => n.key.name === 'watchOptions').forEach( (prop) => { - Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { - if(watchOptionTypes.includes(watchOption)) { - if(typeof(webpackProperties['watchOptions'][watchOption]) === 'number') { - prop.value.properties.push( - j.property( - 'init', - j.identifier(watchOption), - j.literal(webpackProperties['watchOptions'][watchOption]) - ) - ); - } else { - prop.value.properties.push( - j.property( - 'init', - j.identifier(watchOption), - j.identifier(webpackProperties['watchOptions'][watchOption]) - ) - ); - } + const watchOptions = webpackProperties['watchOptions']; + const propValue = j.objectExpression( + Object.keys(watchOptions).map(option => { + if (watchOptionTypes.includes(option)) { + return j.property('init', j.identifier(option), + transformUtils.createIdentifierOrLiteral(j, watchOptions[option])); } else { - throw new Error('Unknown Property', watchOption); + throw new Error('Unknown Property', option); } - }); - }); + }) + ); + transformUtils.checkIfExistsAndAddValue(j, p, 'watchOptions', propValue); } if(webpackProperties['watchOptions'] && webpackProperties['watchOptions']) { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchOptionsProperty)); From 889400c7bb68532009c4ee70d4ee8f5cdc237de2 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 18 Apr 2017 18:37:28 +0200 Subject: [PATCH 052/101] feat: add new tests for entry & regex for validateOptions --- .../entry/__snapshots__/entry.test.js.snap | 14 ++++++++++++++ lib/creator/transformations/entry/entry.test.js | 2 ++ lib/creator/utils/validate-options.spec.js | 2 +- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap index 76ee2c05268..e25c3d9cc8e 100644 --- a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap +++ b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap @@ -23,3 +23,17 @@ exports[`entry transforms correctly using "entry-0" data 3`] = ` } " `; + +exports[`entry transforms correctly using "entry-0" data 4`] = ` +"module.exports = { + entry: () => 'index.js' +} +" +`; + +exports[`entry transforms correctly using "entry-0" data 5`] = ` +"module.exports = { + entry: () => new Promise((resolve) => resolve(['./app', './router'])) +} +" +`; diff --git a/lib/creator/transformations/entry/entry.test.js b/lib/creator/transformations/entry/entry.test.js index ace89d6c8ee..3a754ad8cbd 100644 --- a/lib/creator/transformations/entry/entry.test.js +++ b/lib/creator/transformations/entry/entry.test.js @@ -6,3 +6,5 @@ defineTest(__dirname, 'entry', 'entry-0', {entry: { index: '\'index.js\'', app: '\'app.js\'' }}); +defineTest(__dirname, 'entry', 'entry-0', {entry: '() => \'index.js\''}); +defineTest(__dirname, 'entry', 'entry-0', {entry: '() => new Promise((resolve) => resolve([\'./app\', \'./router\']))'}); diff --git a/lib/creator/utils/validate-options.spec.js b/lib/creator/utils/validate-options.spec.js index fc2c0ef0f4f..aae91533562 100644 --- a/lib/creator/utils/validate-options.spec.js +++ b/lib/creator/utils/validate-options.spec.js @@ -13,7 +13,7 @@ describe('validate-options', () => { it('should find the real files', () => { expect(() => { validateOptions({entry: 'package.json'}); - }).not.toThrowError('Did not find the file'); + }).not.toThrowError(/'Did not find the file'/); }); }); From a9584862c16e316374c663b4def820477e5511a8 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 18 Apr 2017 18:48:10 +0200 Subject: [PATCH 053/101] feat: more tests for obj ref Adds more tests to object references and the context transform --- .../context/__snapshots__/context.test.js.snap | 13 ++++++++++++- .../context/__testfixtures__/context-2.input.js | 7 +++++++ lib/creator/transformations/context/context.test.js | 3 ++- .../entry/__snapshots__/entry.test.js.snap | 7 +++++++ lib/creator/transformations/entry/entry.test.js | 1 + 5 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 lib/creator/transformations/context/__testfixtures__/context-2.input.js diff --git a/lib/creator/transformations/context/__snapshots__/context.test.js.snap b/lib/creator/transformations/context/__snapshots__/context.test.js.snap index 40b90bf1348..167d239e4fb 100644 --- a/lib/creator/transformations/context/__snapshots__/context.test.js.snap +++ b/lib/creator/transformations/context/__snapshots__/context.test.js.snap @@ -18,7 +18,18 @@ exports[`context transforms correctly using "context-1" data 1`] = ` output: { filename: 'bundle.js' }, - context: path.resolve(__dirname, \\"app\\") + context: './some/fake/path' +} +" +`; + +exports[`context transforms correctly using "context-2" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + context: contextVariable } " `; diff --git a/lib/creator/transformations/context/__testfixtures__/context-2.input.js b/lib/creator/transformations/context/__testfixtures__/context-2.input.js new file mode 100644 index 00000000000..f65ad38f034 --- /dev/null +++ b/lib/creator/transformations/context/__testfixtures__/context-2.input.js @@ -0,0 +1,7 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + context: {} +} diff --git a/lib/creator/transformations/context/context.test.js b/lib/creator/transformations/context/context.test.js index 5179fd44201..935a0c09239 100644 --- a/lib/creator/transformations/context/context.test.js +++ b/lib/creator/transformations/context/context.test.js @@ -1,4 +1,5 @@ const defineTest = require('../../../transformations/defineTest'); defineTest(__dirname, 'context', 'context-0', {context : 'path.resolve(__dirname, "app")'}); -defineTest(__dirname, 'context', 'context-1', {context : 'path.resolve(__dirname, "app")'}); +defineTest(__dirname, 'context', 'context-1', {context : '\'./some/fake/path\''}); +defineTest(__dirname, 'context', 'context-2', {context : 'contextVariable'}); diff --git a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap index e25c3d9cc8e..62fe7f7ccf6 100644 --- a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap +++ b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap @@ -37,3 +37,10 @@ exports[`entry transforms correctly using "entry-0" data 5`] = ` } " `; + +exports[`entry transforms correctly using "entry-0" data 6`] = ` +"module.exports = { + entry: entryStringVariable +} +" +`; diff --git a/lib/creator/transformations/entry/entry.test.js b/lib/creator/transformations/entry/entry.test.js index 3a754ad8cbd..8252e5931d6 100644 --- a/lib/creator/transformations/entry/entry.test.js +++ b/lib/creator/transformations/entry/entry.test.js @@ -8,3 +8,4 @@ defineTest(__dirname, 'entry', 'entry-0', {entry: { }}); defineTest(__dirname, 'entry', 'entry-0', {entry: '() => \'index.js\''}); defineTest(__dirname, 'entry', 'entry-0', {entry: '() => new Promise((resolve) => resolve([\'./app\', \'./router\']))'}); +defineTest(__dirname, 'entry', 'entry-0', {entry: 'entryStringVariable'}); From 69725c86fa13666ff65b87fa9063920a1bad248b Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 18 Apr 2017 19:06:58 +0200 Subject: [PATCH 054/101] fix: fix devtool property and add tests for it --- .../__snapshots__/devtool.test.js.snap | 23 +++++++++++++++---- .../__testfixtures__/devtools-2.input.js | 7 ++++++ .../transformations/devtool/devtool.js | 7 ++++-- .../transformations/devtool/devtool.test.js | 5 ++-- 4 files changed, 34 insertions(+), 8 deletions(-) create mode 100644 lib/creator/transformations/devtool/__testfixtures__/devtools-2.input.js diff --git a/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap index 1915162eb06..df085afa042 100644 --- a/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap +++ b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap @@ -7,18 +7,33 @@ exports[`devtool transforms correctly using "devtools-0" data 1`] = ` filename: 'bundle.js' }, - devtools: 'source-map' + devtool: 'source-map' } " `; exports[`devtool transforms correctly using "devtools-1" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - devtools: 'source-map' + + devtools: 'eval', + devtool: 'cheap-module-source-map' +} +" +`; + +exports[`devtool transforms correctly using "devtools-2" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + devtools: {}, + devtool: myVariable } " `; diff --git a/lib/creator/transformations/devtool/__testfixtures__/devtools-2.input.js b/lib/creator/transformations/devtool/__testfixtures__/devtools-2.input.js new file mode 100644 index 00000000000..182aa272de8 --- /dev/null +++ b/lib/creator/transformations/devtool/__testfixtures__/devtools-2.input.js @@ -0,0 +1,7 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + devtools: {} +} diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index f8dc86b7f16..910e0c7d4d7 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -5,8 +5,11 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createDevToolProperty(p) { - const propValue = j.literal(webpackProperties['devtool']); - transformUtils.checkIfExistsAndAddValue(j, p, 'devtools', propValue); + return p.value.properties.push( + j.property('init', + j.identifier('devtool'), + transformUtils.createIdentifierOrLiteral(j, webpackProperties['devtool'])) + ); } if(webpackProperties['devtool'] && webpackProperties['devtool'].length) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/devtool/devtool.test.js b/lib/creator/transformations/devtool/devtool.test.js index 45d21618e87..e1a822406b8 100644 --- a/lib/creator/transformations/devtool/devtool.test.js +++ b/lib/creator/transformations/devtool/devtool.test.js @@ -1,4 +1,5 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'devtool', 'devtools-0', {devtool : 'source-map'}); -defineTest(__dirname, 'devtool', 'devtools-1', {devtool : 'source-map'}); +defineTest(__dirname, 'devtool', 'devtools-0', {devtool : '\'source-map\''}); +defineTest(__dirname, 'devtool', 'devtools-1', {devtool : '\'cheap-module-source-map\''}); +defineTest(__dirname, 'devtool', 'devtools-2', {devtool : 'myVariable'}); From 8f8bd7d8591c3967d4d40d4396f3fd76cf764d84 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 18 Apr 2017 20:29:19 +0200 Subject: [PATCH 055/101] add externals test and fix identifier util Adds tests to externals, some fixes to the externals transform as well as a fix to utils, where it becomes a literal despite being an identifier. --- .../__snapshots__/devtool.test.js.snap | 18 ++- .../__testfixtures__/devtools-1.input.js | 7 -- .../transformations/devtool/devtool.js | 2 +- .../transformations/devtool/devtool.test.js | 5 +- .../__snapshots__/externals.test.js.snap | 109 ++++++++++++++++++ .../__testfixtures__/externals-1.input.js} | 3 +- .../transformations/externals/externals.js | 38 +++++- .../externals/externals.test.js | 49 +++++++- lib/transformations/utils.js | 19 ++- 9 files changed, 228 insertions(+), 22 deletions(-) delete mode 100644 lib/creator/transformations/devtool/__testfixtures__/devtools-1.input.js rename lib/creator/transformations/{devtool/__testfixtures__/devtools-2.input.js => externals/__testfixtures__/externals-1.input.js} (80%) diff --git a/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap index df085afa042..d496d051302 100644 --- a/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap +++ b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap @@ -12,28 +12,38 @@ exports[`devtool transforms correctly using "devtools-0" data 1`] = ` " `; -exports[`devtool transforms correctly using "devtools-1" data 1`] = ` +exports[`devtool transforms correctly using "devtools-0" data 2`] = ` "module.exports = { entry: 'index.js', output: { filename: 'bundle.js' }, - devtools: 'eval', devtool: 'cheap-module-source-map' } " `; -exports[`devtool transforms correctly using "devtools-2" data 1`] = ` +exports[`devtool transforms correctly using "devtools-0" data 3`] = ` "module.exports = { entry: 'index.js', output: { filename: 'bundle.js' }, - devtools: {}, devtool: myVariable } " `; + +exports[`devtool transforms correctly using "devtools-0" data 4`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + devtool: false +} +" +`; diff --git a/lib/creator/transformations/devtool/__testfixtures__/devtools-1.input.js b/lib/creator/transformations/devtool/__testfixtures__/devtools-1.input.js deleted file mode 100644 index 4d2b2302b9b..00000000000 --- a/lib/creator/transformations/devtool/__testfixtures__/devtools-1.input.js +++ /dev/null @@ -1,7 +0,0 @@ -module.exports = { - entry: 'index.js', - output: { - filename: 'bundle.js' - }, - devtools: 'eval' -} diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index 910e0c7d4d7..da4d12146dd 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -11,7 +11,7 @@ module.exports = function(j, ast, yeomanConfig) { transformUtils.createIdentifierOrLiteral(j, webpackProperties['devtool'])) ); } - if(webpackProperties['devtool'] && webpackProperties['devtool'].length) { + if(webpackProperties['devtool']) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(p, createDevToolProperty)); } else { diff --git a/lib/creator/transformations/devtool/devtool.test.js b/lib/creator/transformations/devtool/devtool.test.js index e1a822406b8..a3dc33ee544 100644 --- a/lib/creator/transformations/devtool/devtool.test.js +++ b/lib/creator/transformations/devtool/devtool.test.js @@ -1,5 +1,6 @@ const defineTest = require('../../../transformations/defineTest'); defineTest(__dirname, 'devtool', 'devtools-0', {devtool : '\'source-map\''}); -defineTest(__dirname, 'devtool', 'devtools-1', {devtool : '\'cheap-module-source-map\''}); -defineTest(__dirname, 'devtool', 'devtools-2', {devtool : 'myVariable'}); +defineTest(__dirname, 'devtool', 'devtools-0', {devtool : '\'cheap-module-source-map\''}); +defineTest(__dirname, 'devtool', 'devtools-0', {devtool : 'myVariable'}); +defineTest(__dirname, 'devtool', 'devtools-0', {devtool : 'false'}); diff --git a/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap b/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap index 344c58e1a2e..a802cea638d 100644 --- a/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap +++ b/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap @@ -11,3 +11,112 @@ exports[`externals transforms correctly using "externals-0" data 1`] = ` } " `; + +exports[`externals transforms correctly using "externals-1" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + externals: { + jquery: 'jQuery', + react: 'react' + } +} +" +`; + +exports[`externals transforms correctly using "externals-1" data 2`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + externals: myObj +} +" +`; + +exports[`externals transforms correctly using "externals-1" data 3`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + externals: { + jquery: 'jQuery', + react: reactObj + } +} +" +`; + +exports[`externals transforms correctly using "externals-1" data 4`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + externals: { + jquery: 'jQuery', + react: [reactObj, path.join(__dirname, 'app'), 'jquery'] + } +} +" +`; + +exports[`externals transforms correctly using "externals-1" data 5`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + externals: { + lodash: { + commonjs: 'lodash', + amd: 'lodash', + root: '_' + } + } +} +" +`; + +exports[`externals transforms correctly using "externals-1" data 6`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + externals: { + lodash: { + commonjs: lodash, + amd: hidash, + root: _ + } + } +} +" +`; + +exports[`externals transforms correctly using "externals-1" data 7`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + externals: [{ + a: false, + b: true, + './ext': ./hey + }, function(context, request, callback) {if (/^yourregex$/.test(request)){return callback(null, 'commonjs ' + request);}callback();}] +} +" +`; diff --git a/lib/creator/transformations/devtool/__testfixtures__/devtools-2.input.js b/lib/creator/transformations/externals/__testfixtures__/externals-1.input.js similarity index 80% rename from lib/creator/transformations/devtool/__testfixtures__/devtools-2.input.js rename to lib/creator/transformations/externals/__testfixtures__/externals-1.input.js index 182aa272de8..ea0822c2484 100644 --- a/lib/creator/transformations/devtool/__testfixtures__/devtools-2.input.js +++ b/lib/creator/transformations/externals/__testfixtures__/externals-1.input.js @@ -2,6 +2,5 @@ module.exports = { entry: 'index.js', output: { filename: 'bundle.js' - }, - devtools: {} + } } diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index c8ec0f306f8..1a8976b2cc2 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -8,6 +8,42 @@ module.exports = function(j, ast, yeomanConfig) { j.property('init', j.identifier('externals'), j.literal(webpackProperties.externals)) ); } + else if(typeof(webpackProperties.externals) === 'string') { + return p.value.properties.push( + j.property( + 'init', + j.identifier('externals'), + transformUtils.createIdentifierOrLiteral(j, webpackProperties.externals) + ) + ); + } + else if(Array.isArray(webpackProperties.externals)) { + const externalArray = j.property( + 'init', + j.identifier('externals'), + j.arrayExpression([]) + ); + webpackProperties.externals.forEach( (n) => { + // [{myprop: 'hello'}] + let objectOfArray = j.objectExpression([]); + if(typeof(n) !== 'string') { + for(let key in n) { + objectOfArray.properties.push( + j.property( + 'init', + j.identifier(key), + transformUtils.createIdentifierOrLiteral(j, n[key]) + ) + ); + } + externalArray.value.elements.push(objectOfArray); + } else { + // [val] + return externalArray.value.elements.push(transformUtils.createIdentifierOrLiteral(j, n)); + } + }); + return p.value.properties.push(externalArray); + } else { p.value.properties.push( j.property('init', j.identifier('externals'), j.objectExpression([])) @@ -75,7 +111,7 @@ module.exports = function(j, ast, yeomanConfig) { }); }); } - if(webpackProperties['externals'] && typeof webpackProperties['externals'] === 'object') { + if(webpackProperties['externals']) { return ast.find(j.ObjectExpression) .filter(p => transformUtils.safeTraverse(p , ['parent', 'value', 'left', 'property', 'name']) === 'exports') .forEach(createExternalProperty); diff --git a/lib/creator/transformations/externals/externals.test.js b/lib/creator/transformations/externals/externals.test.js index 85975ec1102..4e5ad0938ae 100644 --- a/lib/creator/transformations/externals/externals.test.js +++ b/lib/creator/transformations/externals/externals.test.js @@ -1,3 +1,50 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'externals', 'externals-0', {externals : /react/}); +defineTest(__dirname, 'externals', 'externals-0', {externals: /react/}); +defineTest(__dirname, 'externals', 'externals-1', {externals: { + jquery: '\'jQuery\'', + react: '\'react\'' +}}); + +defineTest(__dirname, 'externals', 'externals-1', {externals: 'myObj'}); + +defineTest(__dirname, 'externals', 'externals-1', {externals: { + jquery: '\'jQuery\'', + react: 'reactObj' +}}); + +defineTest(__dirname, 'externals', 'externals-1', {externals: { + jquery: '\'jQuery\'', + react: ['reactObj', 'path.join(__dirname, \'app\')', '\'jquery\''] +}}); + +defineTest(__dirname, 'externals', 'externals-1', {externals: { + lodash: { + commonjs: '\'lodash\'', + amd: '\'lodash\'', + root: '\'_\'' + } +}}); + +defineTest(__dirname, 'externals', 'externals-1', {externals: { + lodash: { + commonjs: 'lodash', + amd: 'hidash', + root: '_' + } +}}); + +defineTest(__dirname, 'externals', 'externals-1', {externals: [ + { + a: 'false', + b: 'true', + '\'./ext\'': './hey' + }, + 'function(context, request, callback) {' + + 'if (/^yourregex$/.test(request)){' + + 'return callback(null, \'commonjs \' + request);' + + '}' + + 'callback();' + + '}' +] +}); diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index 46b21c788ab..5e2fee753b0 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -126,13 +126,24 @@ function createIdentifierOrLiteral(j, val) { // We'll need String to native type conversions if (typeof val === 'string') { // 'true' => true - if (val === 'true') literalVal = true; + if (val === 'true') { + literalVal = true; + return j.literal(literalVal); + } // 'false' => false - if (val === 'false') literalVal = false; + if (val === 'false') { + literalVal = false; + return j.literal(literalVal); + } // '1' => 1 - if (!isNaN(Number(val))) literalVal = Number(val); + if (!isNaN(Number(val))) { + literalVal = Number(val); + return j.literal(literalVal); + } // Use identifier instead - else return j.identifier(literalVal); + else { + return j.identifier(literalVal); + } } return j.literal(literalVal); } From 7ca1948aaa173551f5ec49ddc029a58da69ecbca Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 18 Apr 2017 20:34:13 +0200 Subject: [PATCH 056/101] feat: add test to array with obj reference in ext --- .../__snapshots__/externals.test.js.snap | 15 +++++++++++++++ .../transformations/externals/externals.test.js | 11 +++++++++++ 2 files changed, 26 insertions(+) diff --git a/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap b/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap index a802cea638d..1a77ae06b34 100644 --- a/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap +++ b/lib/creator/transformations/externals/__snapshots__/externals.test.js.snap @@ -120,3 +120,18 @@ exports[`externals transforms correctly using "externals-1" data 7`] = ` } " `; + +exports[`externals transforms correctly using "externals-1" data 8`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + externals: [ + myObj, + function(context, request, callback) {if (/^yourregex$/.test(request)){return callback(null, 'commonjs ' + request);}callback();} + ] +} +" +`; diff --git a/lib/creator/transformations/externals/externals.test.js b/lib/creator/transformations/externals/externals.test.js index 4e5ad0938ae..9940e02c417 100644 --- a/lib/creator/transformations/externals/externals.test.js +++ b/lib/creator/transformations/externals/externals.test.js @@ -48,3 +48,14 @@ defineTest(__dirname, 'externals', 'externals-1', {externals: [ '}' ] }); + +defineTest(__dirname, 'externals', 'externals-1', {externals: [ + 'myObj', + 'function(context, request, callback) {' + + 'if (/^yourregex$/.test(request)){' + + 'return callback(null, \'commonjs \' + request);' + + '}' + + 'callback();' + + '}' +] +}); From e455a3317de3083a0a9c9d076e366b912b1644c4 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Thu, 20 Apr 2017 17:27:35 +0200 Subject: [PATCH 057/101] fix: fix silly mistake on devtools props Sorry Pavithra.. --- .../__snapshots__/devtool.test.js.snap | 24 +++++++++---------- ...devtools-0.input.js => devtool-0.input.js} | 0 .../__testfixtures__/devtool-1.input.js | 7 ++++++ .../transformations/devtool/devtool.js | 7 ++---- .../transformations/devtool/devtool.test.js | 8 +++---- 5 files changed, 24 insertions(+), 22 deletions(-) rename lib/creator/transformations/devtool/__testfixtures__/{devtools-0.input.js => devtool-0.input.js} (100%) create mode 100644 lib/creator/transformations/devtool/__testfixtures__/devtool-1.input.js diff --git a/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap index d496d051302..b1835ac1085 100644 --- a/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap +++ b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`devtool transforms correctly using "devtools-0" data 1`] = ` +exports[`devtool transforms correctly using "devtool-0" data 1`] = ` "module.exports = { entry: 'index.js', output: { @@ -12,38 +12,36 @@ exports[`devtool transforms correctly using "devtools-0" data 1`] = ` " `; -exports[`devtool transforms correctly using "devtools-0" data 2`] = ` +exports[`devtool transforms correctly using "devtool-0" data 2`] = ` "module.exports = { entry: 'index.js', output: { filename: 'bundle.js' }, - devtool: 'cheap-module-source-map' + devtool: myVariable } " `; -exports[`devtool transforms correctly using "devtools-0" data 3`] = ` +exports[`devtool transforms correctly using "devtool-1" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - - devtool: myVariable + devtool: 'cheap-module-source-map' } " `; -exports[`devtool transforms correctly using "devtools-0" data 4`] = ` +exports[`devtool transforms correctly using "devtool-1" data 2`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - - devtool: false + devtool: false } " `; diff --git a/lib/creator/transformations/devtool/__testfixtures__/devtools-0.input.js b/lib/creator/transformations/devtool/__testfixtures__/devtool-0.input.js similarity index 100% rename from lib/creator/transformations/devtool/__testfixtures__/devtools-0.input.js rename to lib/creator/transformations/devtool/__testfixtures__/devtool-0.input.js diff --git a/lib/creator/transformations/devtool/__testfixtures__/devtool-1.input.js b/lib/creator/transformations/devtool/__testfixtures__/devtool-1.input.js new file mode 100644 index 00000000000..d7fc037f215 --- /dev/null +++ b/lib/creator/transformations/devtool/__testfixtures__/devtool-1.input.js @@ -0,0 +1,7 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + devtool: 'eval' +} diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index da4d12146dd..faed2a22ab8 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -5,11 +5,8 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createDevToolProperty(p) { - return p.value.properties.push( - j.property('init', - j.identifier('devtool'), - transformUtils.createIdentifierOrLiteral(j, webpackProperties['devtool'])) - ); + const propValue = transformUtils.createIdentifierOrLiteral(j, webpackProperties['devtool']); + return transformUtils.checkIfExistsAndAddValue(j, p, 'devtool', propValue); } if(webpackProperties['devtool']) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/devtool/devtool.test.js b/lib/creator/transformations/devtool/devtool.test.js index a3dc33ee544..59b01a1d92b 100644 --- a/lib/creator/transformations/devtool/devtool.test.js +++ b/lib/creator/transformations/devtool/devtool.test.js @@ -1,6 +1,6 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'devtool', 'devtools-0', {devtool : '\'source-map\''}); -defineTest(__dirname, 'devtool', 'devtools-0', {devtool : '\'cheap-module-source-map\''}); -defineTest(__dirname, 'devtool', 'devtools-0', {devtool : 'myVariable'}); -defineTest(__dirname, 'devtool', 'devtools-0', {devtool : 'false'}); +defineTest(__dirname, 'devtool', 'devtool-0', {devtool : '\'source-map\''}); +defineTest(__dirname, 'devtool', 'devtool-0', {devtool : 'myVariable'}); +defineTest(__dirname, 'devtool', 'devtool-1', {devtool : '\'cheap-module-source-map\''}); +defineTest(__dirname, 'devtool', 'devtool-1', {devtool : 'false'}); From 583520e17cd5e482396036e746728bdda948dfc1 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Thu, 20 Apr 2017 19:05:36 +0200 Subject: [PATCH 058/101] tests: add tests for every transform --- lib/creator/transformations/index.js | 2 +- .../module/__snapshots__/module.test.js.snap | 62 +++++++++++++++++++ .../module/__testfixtures__/module-0.input.js | 6 ++ .../module/__testfixtures__/module-1.input.js | 6 ++ lib/creator/transformations/module/module.js | 2 +- .../transformations/module/module.test.js | 45 ++++++++++++++ .../output/__snapshots__/output.test.js.snap | 18 ++++++ .../output/__testfixtures__/output-0.input.js | 3 + .../transformations/output/output.test.js | 13 ++++ .../__snapshots__/performance.test.js.snap | 18 ++++++ .../__testfixtures__/performance-0.input.js | 6 ++ .../performance/performance.test.js | 10 +++ .../__snapshots__/resolve.test.js.snap | 37 +++++++++++ .../__testfixtures__/resolve-0.input.js | 6 ++ .../transformations/resolve/resolve.test.js | 25 ++++++++ .../stats/__snapshots__/stats.test.js.snap | 55 ++++++++++++++++ .../stats/__testfixtures__/stats-0.input.js | 6 ++ lib/creator/transformations/stats/stats.js | 3 +- .../transformations/stats/stats.test.js | 34 ++++++++++ .../__snapshots__/top-scope.test.js.snap | 7 +++ .../__testfixtures__/top-scope-0.input.js | 1 + .../index.js => top-scope/top-scope.js} | 0 .../top-scope/top-scope.test.js | 5 ++ lib/transformations/defineTest.js | 10 ++- 24 files changed, 374 insertions(+), 6 deletions(-) create mode 100644 lib/creator/transformations/module/__snapshots__/module.test.js.snap create mode 100644 lib/creator/transformations/module/__testfixtures__/module-0.input.js create mode 100644 lib/creator/transformations/module/__testfixtures__/module-1.input.js create mode 100644 lib/creator/transformations/module/module.test.js create mode 100644 lib/creator/transformations/output/__snapshots__/output.test.js.snap create mode 100644 lib/creator/transformations/output/__testfixtures__/output-0.input.js create mode 100644 lib/creator/transformations/output/output.test.js create mode 100644 lib/creator/transformations/performance/__snapshots__/performance.test.js.snap create mode 100644 lib/creator/transformations/performance/__testfixtures__/performance-0.input.js create mode 100644 lib/creator/transformations/performance/performance.test.js create mode 100644 lib/creator/transformations/resolve/__snapshots__/resolve.test.js.snap create mode 100644 lib/creator/transformations/resolve/__testfixtures__/resolve-0.input.js create mode 100644 lib/creator/transformations/resolve/resolve.test.js create mode 100644 lib/creator/transformations/stats/__snapshots__/stats.test.js.snap create mode 100644 lib/creator/transformations/stats/__testfixtures__/stats-0.input.js create mode 100644 lib/creator/transformations/stats/stats.test.js create mode 100644 lib/creator/transformations/top-scope/__snapshots__/top-scope.test.js.snap create mode 100644 lib/creator/transformations/top-scope/__testfixtures__/top-scope-0.input.js rename lib/creator/transformations/{topScope/index.js => top-scope/top-scope.js} (100%) create mode 100644 lib/creator/transformations/top-scope/top-scope.test.js diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 2ba56d42bcd..36660510f7b 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -25,7 +25,7 @@ const profileTransform = require('./other/profile'); const mergeTransform = require('./other/merge'); const moduleTransform = require('./module/module'); const pluginsTransform = require('./plugins/plugins'); -const topScopeTransform = require('./topScope/index'); +const topScopeTransform = require('./top-scope/top-scope'); /* * @function runTransform diff --git a/lib/creator/transformations/module/__snapshots__/module.test.js.snap b/lib/creator/transformations/module/__snapshots__/module.test.js.snap new file mode 100644 index 00000000000..dbeaa8ca535 --- /dev/null +++ b/lib/creator/transformations/module/__snapshots__/module.test.js.snap @@ -0,0 +1,62 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`module transforms correctly using "module-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + module: { + rules: [{ + test: /\\\\.(js|vue)$/, + loader: 'eslint-loader', + enforce: 'pre', + include: [customObj, 'Stringy'], + options: { + formatter: 'someOption' + } + }, { + test: /\\\\.vue$/, + loader: 'vue-loader', + options: vueObject + }, { + test: /\\\\.js$/, + loader: 'babel-loader', + include: [resolve('src'), resolve('test')] + }, { + test: /\\\\.(png|jpe?g|gif|svg)(\\\\?.*)?$/, + loader: 'url-loader', + options: { + limit: 10000, + name: utils.assetsPath('img/[name].[hash:7].[ext]') + } + }, { + test: /\\\\.(woff2?|eot|ttf|otf)(\\\\?.*)?$/, + loader: 'url-loader', + options: { + limit: 10000, + name: utils.assetsPath('fonts/[name].[hash:7].[ext]') + } + }] + } +} +" +`; + +exports[`module transforms correctly using "module-1" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + module: { + noParse: /jquery|lodash/, + rules: [{ + test: /\\\\.js$/ + }] + } +} +" +`; diff --git a/lib/creator/transformations/module/__testfixtures__/module-0.input.js b/lib/creator/transformations/module/__testfixtures__/module-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/module/__testfixtures__/module-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/module/__testfixtures__/module-1.input.js b/lib/creator/transformations/module/__testfixtures__/module-1.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/module/__testfixtures__/module-1.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 6e69093eac9..c22027070db 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -96,7 +96,7 @@ module.exports = function(j, ast, yeomanConfig) { pushProperty = j.identifier(webpackProperties.module[webpackProp]); } // module.rules is an external object - prop.value.properties.push( + return prop.value.properties.push( j.property( 'init', j.identifier(webpackProp), diff --git a/lib/creator/transformations/module/module.test.js b/lib/creator/transformations/module/module.test.js new file mode 100644 index 00000000000..300788d6bf8 --- /dev/null +++ b/lib/creator/transformations/module/module.test.js @@ -0,0 +1,45 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'module', 'module-0', {module: { + rules: [{ + test: new RegExp(/\.(js|vue)$/), + loader: '\'eslint-loader\'', + enforce: '\'pre\'', + include: ['customObj', '\'Stringy\''], + options: { + formatter: '\'someOption\'' + } + }, { + test: new RegExp(/\.vue$/), + loader: '\'vue-loader\'', + options: 'vueObject' + }, { + test: new RegExp(/\.js$/), + loader: '\'babel-loader\'', + include: ['resolve(\'src\')', 'resolve(\'test\')'] + }, { + test: new RegExp(/\.(png|jpe?g|gif|svg)(\?.*)?$/), + loader: '\'url-loader\'', + options: { + limit: 10000, + name: 'utils.assetsPath(\'img/[name].[hash:7].[ext]\')' + } + }, { + test: new RegExp(/\.(woff2?|eot|ttf|otf)(\?.*)?$/), + loader: '\'url-loader\'', + options: { + limit: '10000', + name: 'utils.assetsPath(\'fonts/[name].[hash:7].[ext]\')' + } + }] +}}); + +defineTest(__dirname, 'module', 'module-1', {module: { + noParse: /jquery|lodash/, + rules: [{ + test: new RegExp(/\.js$/), + parser: { + amd: false + } + }] +}}); diff --git a/lib/creator/transformations/output/__snapshots__/output.test.js.snap b/lib/creator/transformations/output/__snapshots__/output.test.js.snap new file mode 100644 index 00000000000..9c51ca710ee --- /dev/null +++ b/lib/creator/transformations/output/__snapshots__/output.test.js.snap @@ -0,0 +1,18 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`output transforms correctly using "output-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle', + path: 'dist/assets', + pathinfo: true, + publicPath: 'https://google.com', + sourceMapFilename: '[name].map', + sourcePrefix: '\\\\t', + umdNamedDefine: true, + strictModuleExceptionHandling: true + } +} +" +`; diff --git a/lib/creator/transformations/output/__testfixtures__/output-0.input.js b/lib/creator/transformations/output/__testfixtures__/output-0.input.js new file mode 100644 index 00000000000..a9899df14fa --- /dev/null +++ b/lib/creator/transformations/output/__testfixtures__/output-0.input.js @@ -0,0 +1,3 @@ +module.exports = { + entry: 'index.js' +} diff --git a/lib/creator/transformations/output/output.test.js b/lib/creator/transformations/output/output.test.js new file mode 100644 index 00000000000..bbe83bf8394 --- /dev/null +++ b/lib/creator/transformations/output/output.test.js @@ -0,0 +1,13 @@ +const defineTest = require('../../../transformations/defineTest'); +const jscodeshift = require('jscodeshift'); + +defineTest(__dirname, 'output', 'output-0', {output: { + filename: '\'bundle\'', + path: '\'dist/assets\'', + pathinfo: true, + publicPath: '\'https://google.com\'', + sourceMapFilename: '\'[name].map\'', + sourcePrefix: jscodeshift('\'\t\''), + umdNamedDefine: true, + strictModuleExceptionHandling: true +}}); diff --git a/lib/creator/transformations/performance/__snapshots__/performance.test.js.snap b/lib/creator/transformations/performance/__snapshots__/performance.test.js.snap new file mode 100644 index 00000000000..93bd117add3 --- /dev/null +++ b/lib/creator/transformations/performance/__snapshots__/performance.test.js.snap @@ -0,0 +1,18 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`performance transforms correctly using "performance-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + performance: { + hints: 'warning', + maxEntrypointSize: 400000, + maxAssetSize: 100000, + assetFilter: function(assetFilename) {return assetFilename.endsWith('.js');} + } +} +" +`; diff --git a/lib/creator/transformations/performance/__testfixtures__/performance-0.input.js b/lib/creator/transformations/performance/__testfixtures__/performance-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/performance/__testfixtures__/performance-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/performance/performance.test.js b/lib/creator/transformations/performance/performance.test.js new file mode 100644 index 00000000000..0eca6e8ed00 --- /dev/null +++ b/lib/creator/transformations/performance/performance.test.js @@ -0,0 +1,10 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'performance', 'performance-0', {performance: { + hints: '\'warning\'', + maxEntrypointSize: 400000, + maxAssetSize: 100000, + assetFilter: 'function(assetFilename) {' + + 'return assetFilename.endsWith(\'.js\');' + + '}' +}}); diff --git a/lib/creator/transformations/resolve/__snapshots__/resolve.test.js.snap b/lib/creator/transformations/resolve/__snapshots__/resolve.test.js.snap new file mode 100644 index 00000000000..7b31d6803d7 --- /dev/null +++ b/lib/creator/transformations/resolve/__snapshots__/resolve.test.js.snap @@ -0,0 +1,37 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`resolve transforms correctly using "resolve-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + resolve: { + alias: { + hello: 'world', + world: hello + }, + + aliasFields: ['browser', wars], + descriptionFiles: ['a', b], + enforceExtension: false, + enforceModuleExtension: false, + extensions: [hey, 'ho'], + mainFields: [main, 'story'], + mainFiles: ['noMainFileHere', iGuess], + modules: [one, 'two'], + unsafeCache: false, + resolveLoader: { + modules: ['node_modules', mode_nodules], + extensions: [jsVal, '.json'], + mainFields: [loader, 'main'], + moduleExtensions: ['-loader', value] + }, + + plugins: [somePlugin, 'stringVal'], + symlinks: true + } +} +" +`; diff --git a/lib/creator/transformations/resolve/__testfixtures__/resolve-0.input.js b/lib/creator/transformations/resolve/__testfixtures__/resolve-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/resolve/__testfixtures__/resolve-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/resolve/resolve.test.js b/lib/creator/transformations/resolve/resolve.test.js new file mode 100644 index 00000000000..95e21123020 --- /dev/null +++ b/lib/creator/transformations/resolve/resolve.test.js @@ -0,0 +1,25 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'resolve', 'resolve-0', {resolve: { + alias: { + hello: '\'world\'', + world: 'hello' + }, + aliasFields: ['\'browser\'', 'wars'], + descriptionFiles: ['\'a\'', 'b'], + enforceExtension: false, + enforceModuleExtension: false, + extensions: ['hey', '\'ho\''], + mainFields: ['main', '\'story\''], + mainFiles: ['\'noMainFileHere\'', 'iGuess'], + modules: ['one', '\'two\''], + unsafeCache: false, + resolveLoader: { + modules: ['\'node_modules\'', 'mode_nodules'], + extensions: ['jsVal', '\'.json\''], + mainFields: ['loader', '\'main\''], + moduleExtensions: ['\'-loader\'', 'value'] + }, + plugins: ['somePlugin', '\'stringVal\''], + symlinks: true +}}); diff --git a/lib/creator/transformations/stats/__snapshots__/stats.test.js.snap b/lib/creator/transformations/stats/__snapshots__/stats.test.js.snap new file mode 100644 index 00000000000..b94252a2e01 --- /dev/null +++ b/lib/creator/transformations/stats/__snapshots__/stats.test.js.snap @@ -0,0 +1,55 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`stats transforms correctly using "stats-0" data 1`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + stats: { + assets: true, + assetsSort: 'field', + cached: true, + cachedAssets: true, + children: true, + chunks: true, + chunkModules: true, + chunkOrigins: true, + chunksSort: 'field', + context: '../src/', + colors: true, + depth: false, + entrypoints: customVal, + errors: true, + errorDetails: true, + exclude: [], + hash: true, + maxModules: 15, + modules: true, + modulesSort: 'field', + performance: true, + providedExports: false, + publicPath: true, + reasons: true, + source: true, + timings: true, + usedExports: false, + version: true, + warnings: true + } +} +" +`; + +exports[`stats transforms correctly using "stats-0" data 2`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + stats: 'errors-only' +} +" +`; diff --git a/lib/creator/transformations/stats/__testfixtures__/stats-0.input.js b/lib/creator/transformations/stats/__testfixtures__/stats-0.input.js new file mode 100644 index 00000000000..ea0822c2484 --- /dev/null +++ b/lib/creator/transformations/stats/__testfixtures__/stats-0.input.js @@ -0,0 +1,6 @@ +module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +} diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index 9e19ad95224..d09b23bc0bf 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -1,5 +1,6 @@ const statsTypes = require('./stats-types'); const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; @@ -21,7 +22,7 @@ module.exports = function(j, ast, yeomanConfig) { j.property( 'init', j.identifier(webpackProp), - j.identifier(webpackProperties.stats[webpackProp]) + transformUtils.createIdentifierOrLiteral(j, webpackProperties.stats[webpackProp]) ) ); } diff --git a/lib/creator/transformations/stats/stats.test.js b/lib/creator/transformations/stats/stats.test.js new file mode 100644 index 00000000000..8a6b5a7a91d --- /dev/null +++ b/lib/creator/transformations/stats/stats.test.js @@ -0,0 +1,34 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'stats', 'stats-0', {stats: { + assets: true, + assetsSort: '\'field\'', + cached: true, + cachedAssets: true, + children: true, + chunks: true, + chunkModules: true, + chunkOrigins: true, + chunksSort: '\'field\'', + context: '\'../src/\'', + colors: true, + depth: false, + entrypoints: 'customVal', + errors: true, + errorDetails: true, + exclude: [], + hash: true, + maxModules: 15, + modules: true, + modulesSort: '\'field\'', + performance: true, + providedExports: false, + publicPath: true, + reasons: true, + source: true, + timings: true, + usedExports: false, + version: true, + warnings: true +}}); +defineTest(__dirname, 'stats', 'stats-0', {stats: '\'errors-only\''}); diff --git a/lib/creator/transformations/top-scope/__snapshots__/top-scope.test.js.snap b/lib/creator/transformations/top-scope/__snapshots__/top-scope.test.js.snap new file mode 100644 index 00000000000..9ceb4dcb14e --- /dev/null +++ b/lib/creator/transformations/top-scope/__snapshots__/top-scope.test.js.snap @@ -0,0 +1,7 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`top-scope transforms correctly using "top-scope-0" data 1`] = ` +"var test = 'me'; +module.exports = {} +" +`; diff --git a/lib/creator/transformations/top-scope/__testfixtures__/top-scope-0.input.js b/lib/creator/transformations/top-scope/__testfixtures__/top-scope-0.input.js new file mode 100644 index 00000000000..4ba52ba2c8d --- /dev/null +++ b/lib/creator/transformations/top-scope/__testfixtures__/top-scope-0.input.js @@ -0,0 +1 @@ +module.exports = {} diff --git a/lib/creator/transformations/topScope/index.js b/lib/creator/transformations/top-scope/top-scope.js similarity index 100% rename from lib/creator/transformations/topScope/index.js rename to lib/creator/transformations/top-scope/top-scope.js diff --git a/lib/creator/transformations/top-scope/top-scope.test.js b/lib/creator/transformations/top-scope/top-scope.test.js new file mode 100644 index 00000000000..d7692345ff9 --- /dev/null +++ b/lib/creator/transformations/top-scope/top-scope.test.js @@ -0,0 +1,5 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'top-scope', 'top-scope-0', { topScope: [ + 'var test = \'me\';' +]}); diff --git a/lib/transformations/defineTest.js b/lib/transformations/defineTest.js index 06c16ed7e56..c2ef471e89d 100644 --- a/lib/transformations/defineTest.js +++ b/lib/transformations/defineTest.js @@ -43,9 +43,13 @@ function runSingleTansform(dirName, transformName, testFilePrefix, initOptions) } const ast = jscodeshift(source); if (initOptions) { - return transform(jscodeshift, ast, { - webpackOptions: initOptions - }).toSource({ quote: 'single' }); + if (initOptions.topScope) { + return transform(jscodeshift, ast, initOptions).toSource({ quote: 'single' }); + } else { + return transform(jscodeshift, ast, { + webpackOptions: initOptions + }).toSource({ quote: 'single' }); + } } return transform(jscodeshift, ast, source).toSource({ quote: 'single' }); } From efb80ead47a73f32feb2f78e67eb20ff1aa6757c Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Thu, 20 Apr 2017 23:23:01 +0200 Subject: [PATCH 059/101] feat: add more utility for tests --- .../module/__snapshots__/module.test.js.snap | 3 +- lib/creator/transformations/module/module.js | 3 +- .../transformations/module/module.test.js | 3 +- lib/creator/transformations/module/utils.js | 58 ++++++------------- lib/transformations/utils.js | 55 +++++++++++++++++- 5 files changed, 79 insertions(+), 43 deletions(-) diff --git a/lib/creator/transformations/module/__snapshots__/module.test.js.snap b/lib/creator/transformations/module/__snapshots__/module.test.js.snap index dbeaa8ca535..553eda336d4 100644 --- a/lib/creator/transformations/module/__snapshots__/module.test.js.snap +++ b/lib/creator/transformations/module/__snapshots__/module.test.js.snap @@ -36,7 +36,8 @@ exports[`module transforms correctly using "module-0" data 1`] = ` loader: 'url-loader', options: { limit: 10000, - name: utils.assetsPath('fonts/[name].[hash:7].[ext]') + name: utils.assetsPath('fonts/[name].[hash:7].[ext]'), + someArr: [Hey] } }] } diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index c22027070db..8c37b816f5b 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -1,6 +1,7 @@ const webpackModuleTypes = require('./module-types'); const isAssignment = require('../../utils/is-assignment'); const utils = require('./utils'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; @@ -81,7 +82,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(key === 'include' || key === 'exclude') { moduleProp.value.elements[seen].properties.push( - utils.createIncludeOrExcludeProperties(j, key, subProps) + transformUtils.createArrayWithChildren(j, key, subProps) ); } } diff --git a/lib/creator/transformations/module/module.test.js b/lib/creator/transformations/module/module.test.js index 300788d6bf8..b6e81827d6b 100644 --- a/lib/creator/transformations/module/module.test.js +++ b/lib/creator/transformations/module/module.test.js @@ -29,7 +29,8 @@ defineTest(__dirname, 'module', 'module-0', {module: { loader: '\'url-loader\'', options: { limit: '10000', - name: 'utils.assetsPath(\'fonts/[name].[hash:7].[ext]\')' + name: 'utils.assetsPath(\'fonts/[name].[hash:7].[ext]\')', + someArr: ['Hey'] } }] }}); diff --git a/lib/creator/transformations/module/utils.js b/lib/creator/transformations/module/utils.js index 39634eab720..71682afa9b6 100644 --- a/lib/creator/transformations/module/utils.js +++ b/lib/creator/transformations/module/utils.js @@ -1,3 +1,4 @@ +const transformUtils = require('../../../transformations/utils'); // optional for the user to parse using jscodeshift for only this if a regular regexp doesnt work. function regExpStrategy(j, webpackProperties, webpackProp, prop) { @@ -21,42 +22,31 @@ function createTestProperty(j, moduleProp, seen, key, subProps) { } // Module.rules.myRule.option function createOption(j, subProps, key) { - let optionVal = j.property('init', j.identifier(key), j.identifier('null')); + let optionVal; + let optionProp; if(typeof(subProps[key]) === 'string') { - optionVal.value = j.identifier(subProps[key]); + optionProp = transformUtils.createIdentifierOrLiteral(j, subProps[key]); + optionVal = transformUtils.createPropertyWithSuppliedProperty(j, key, optionProp); } else { - optionVal.value.type = 'ObjectExpression'; - optionVal.value.properties = []; + optionVal = transformUtils.createPropertyWithSuppliedProperty(j, key, j.objectExpression([])); + Object.keys(subProps[key]).forEach( (optionProperty) => { if(Array.isArray(subProps[key][optionProperty])) { - const optionArray = j.property( - 'init', - j.identifier(optionProperty), - j.arrayExpression([]) + const optionArray = transformUtils.createArrayWithChildren( + j, optionProperty, subProps[key][optionProperty], true ); - subProps[key][optionProperty].forEach( (n) => { - optionArray.value.elements.push(j.literal(n)); - }); optionVal.value.properties.push(optionArray); } else { - if(typeof(subProps[key][optionProperty]) === 'string') { - optionVal.value.properties.push( - j.property( - 'init', - j.identifier(optionProperty), - j.identifier(subProps[key][optionProperty]) + optionVal.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty( + j, + optionProperty, + transformUtils.createIdentifierOrLiteral( + j, subProps[key][optionProperty] ) - ); - } else { - optionVal.value.properties.push( - j.property( - 'init', - j.identifier(optionProperty), - j.literal(subProps[key][optionProperty]) - ) - ); - } + ) + ); } }); } @@ -64,7 +54,7 @@ function createOption(j, subProps, key) { } // Module.rules.rule.use function createUseProperties(j, key, subProps) { - let useVal = j.property('init', j.identifier(key), j.arrayExpression([])); + let useVal = transformUtils.createEmptyArrayProperty(j, key); Object.keys(subProps[key]).forEach( (optionProperty) => { if(typeof(subProps[key][optionProperty]) === 'string') { @@ -102,19 +92,9 @@ function createUseProperties(j, key, subProps) { return useVal; } -// Module.rules.include/exclude -function createIncludeOrExcludeProperties(j, key, subProps) { - let InExcludeVal = j.property('init', j.identifier(key), j.arrayExpression([])); - Object.keys(subProps[key]).forEach( (subProperty) => { - InExcludeVal.value.elements.push(j.identifier(subProps[key][subProperty])); - }); - return InExcludeVal; -} - module.exports = { regExpStrategy, createTestProperty, createOption, - createUseProperties, - createIncludeOrExcludeProperties + createUseProperties }; diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index 5e2fee753b0..ef47cd336e3 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -305,6 +305,56 @@ function checkIfExistsAndAddValue(j, node, key, value) { } } +/* +* @function createEmptyArrayProperty +* +* Creates an empty array +* @param j — jscodeshift API +* @param { String } key - st name +* @returns - { Array } arr - An empty array +*/ +function createEmptyArrayProperty(j, key) { + return j.property('init', j.identifier(key), j.arrayExpression([])); +} + +/* +* @function createArrayWithChildren +* +* Creates an array and iterates on an object with properties +* @param j — jscodeshift API +* @param { String } key - object name +* @param { string } subProps - computed value of the property +* @returns - { Array } arr - An array with the object properties +*/ +function createArrayWithChildren(j, key, subProps, shouldDropKeys) { + let arr = createEmptyArrayProperty(j, key); + if(shouldDropKeys) { + subProps.forEach( (subProperty) => { + arr.value.elements.push(createIdentifierOrLiteral(j, subProperty)); + }); + } else { + Object.keys(subProps[key]).forEach( (subProperty) => { + arr.value.elements.push(createIdentifierOrLiteral(j, subProps[key][subProperty])); + }); + } + return arr; +} + +/* +* @function createPropertyWithSuppliedProperty +* +* Creates an property with an supplied property as parameter +* @param j — jscodeshift API +* @param { String } key - object name +* @param { Node } prop - property to be added +* @returns - { Node } - An property with the supplied property +*/ + +function createPropertyWithSuppliedProperty(j,key, prop) { + return j.property('init', j.identifier(key), prop); +} + + module.exports = { safeTraverse, createProperty, @@ -317,5 +367,8 @@ module.exports = { createIdentifierOrLiteral, findObjWithOneOfKeys, getRequire, - checkIfExistsAndAddValue + checkIfExistsAndAddValue, + createArrayWithChildren, + createEmptyArrayProperty, + createPropertyWithSuppliedProperty }; From 6d15a77ad7dbdcd891532a373682b3e72529b38a Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 22 Apr 2017 15:52:59 +0200 Subject: [PATCH 060/101] enhancements: use abstractions & utils --- .../__snapshots__/context.test.js.snap | 14 +- .../__testfixtures__/context-1.input.js | 3 +- .../__testfixtures__/context-2.input.js | 3 +- .../transformations/context/context.js | 9 +- .../transformations/externals/externals.js | 129 ++++++++---------- lib/creator/transformations/module/module.js | 55 ++++---- lib/creator/transformations/module/utils.js | 38 +++--- lib/creator/transformations/node/node.js | 28 ++-- .../other/__snapshots__/others.test.js.snap | 12 ++ lib/creator/transformations/other/amd.js | 29 ++-- lib/creator/transformations/other/bail.js | 7 +- lib/creator/transformations/other/cache.js | 7 +- .../transformations/other/others.test.js | 1 + lib/creator/transformations/other/profile.js | 7 +- lib/creator/transformations/output/output.js | 35 ++--- .../performance/performance.js | 43 +++--- .../transformations/plugins/plugins.js | 9 +- 17 files changed, 227 insertions(+), 202 deletions(-) diff --git a/lib/creator/transformations/context/__snapshots__/context.test.js.snap b/lib/creator/transformations/context/__snapshots__/context.test.js.snap index 167d239e4fb..d707e07cda2 100644 --- a/lib/creator/transformations/context/__snapshots__/context.test.js.snap +++ b/lib/creator/transformations/context/__snapshots__/context.test.js.snap @@ -14,22 +14,24 @@ exports[`context transforms correctly using "context-0" data 1`] = ` exports[`context transforms correctly using "context-1" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - context: './some/fake/path' + + context: './some/fake/path' } " `; exports[`context transforms correctly using "context-2" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - context: contextVariable + + context: contextVariable } " `; diff --git a/lib/creator/transformations/context/__testfixtures__/context-1.input.js b/lib/creator/transformations/context/__testfixtures__/context-1.input.js index 21e6a8a9e4c..ea0822c2484 100644 --- a/lib/creator/transformations/context/__testfixtures__/context-1.input.js +++ b/lib/creator/transformations/context/__testfixtures__/context-1.input.js @@ -2,6 +2,5 @@ module.exports = { entry: 'index.js', output: { filename: 'bundle.js' - }, - context: 'blah' + } } diff --git a/lib/creator/transformations/context/__testfixtures__/context-2.input.js b/lib/creator/transformations/context/__testfixtures__/context-2.input.js index f65ad38f034..ea0822c2484 100644 --- a/lib/creator/transformations/context/__testfixtures__/context-2.input.js +++ b/lib/creator/transformations/context/__testfixtures__/context-2.input.js @@ -2,6 +2,5 @@ module.exports = { entry: 'index.js', output: { filename: 'bundle.js' - }, - context: {} + } } diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index a5b64c1d505..b5a26b516b6 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -5,11 +5,14 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createContextProperty(p) { - const propValue = transformUtils.createIdentifierOrLiteral(j, webpackProperties['context']); - transformUtils.checkIfExistsAndAddValue(j, p, 'context', propValue); + return p.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty( + j, 'context', j.identifier(webpackProperties['context']) + ) + ); } - if(webpackProperties['context'] && webpackProperties['context'].length) { + if(webpackProperties['context']) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(p, createContextProperty)); } else { diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 1a8976b2cc2..b78fffbbca5 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -3,37 +3,27 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createExternalProperty(p) { - if(webpackProperties.externals instanceof RegExp) { - return p.value.properties.push( - j.property('init', j.identifier('externals'), j.literal(webpackProperties.externals)) - ); - } - else if(typeof(webpackProperties.externals) === 'string') { + if(webpackProperties.externals instanceof RegExp || typeof(webpackProperties.externals) === 'string') { + let stringProp = webpackProperties.externals instanceof RegExp ? + j.literal(webpackProperties.externals) : + transformUtils.createIdentifierOrLiteral(j, webpackProperties.externals); + return p.value.properties.push( - j.property( - 'init', - j.identifier('externals'), - transformUtils.createIdentifierOrLiteral(j, webpackProperties.externals) + transformUtils.createPropertyWithSuppliedProperty( + j, 'externals', stringProp ) ); } else if(Array.isArray(webpackProperties.externals)) { - const externalArray = j.property( - 'init', - j.identifier('externals'), - j.arrayExpression([]) - ); + const externalArray = transformUtils.createEmptyArrayProperty(j, 'externals'); webpackProperties.externals.forEach( (n) => { // [{myprop: 'hello'}] let objectOfArray = j.objectExpression([]); if(typeof(n) !== 'string') { for(let key in n) { objectOfArray.properties.push( - j.property( - 'init', - j.identifier(key), - transformUtils.createIdentifierOrLiteral(j, n[key]) - ) + transformUtils.createPropertyWithSuppliedProperty( + j, key, transformUtils.createIdentifierOrLiteral(j, n[key])) ); } externalArray.value.elements.push(objectOfArray); @@ -46,70 +36,67 @@ module.exports = function(j, ast, yeomanConfig) { } else { p.value.properties.push( - j.property('init', j.identifier('externals'), j.objectExpression([])) + transformUtils.createPropertyWithSuppliedProperty( + j, 'externals', j.objectExpression([]) + ) ); - } - let externalsProp = p.value.properties; - externalsProp.filter(n => n.key.name === 'externals').forEach( (prop) => { - Object.keys(webpackProperties['externals']).forEach( (webpackProp) => { - if(Array.isArray(webpackProperties.externals[webpackProp])) { - // if we got a type, we make it an array - const externalArray = j.property( - 'init', - j.identifier(webpackProp), - j.arrayExpression([]) - ); - - webpackProperties.externals[webpackProp].forEach( (n) => { - return externalArray.value.elements.push(j.identifier(n)); - }); - - prop.value.properties.push(externalArray); - } - else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.identifier(webpackProperties.externals[webpackProp])) - ); - } - else { - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.objectExpression([])) - ); - prop.value.properties.forEach( (externalProp) => { - if(externalProp.key.name === webpackProp) { - + let externalsProp = p.value.properties; + externalsProp.filter(n => + (transformUtils.safeTraverse(n, ['key', 'name']) === 'externals') + ).forEach( (prop) => { + Object.keys(webpackProperties['externals']).forEach( (webpackProp) => { + if(Array.isArray(webpackProperties.externals[webpackProp])) { + // if we got a type, we make it an array + const externalArray = transformUtils.createArrayWithChildren( + j, webpackProp, webpackProperties.externals[webpackProp], true + ); + prop.value.properties.push(externalArray); + } + else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { + prop.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty( + j, + webpackProp, + transformUtils.createIdentifierOrLiteral( + j, webpackProperties.externals[webpackProp] + ) + ) + ); + } + else { + prop.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty( + j, webpackProp, j.objectExpression([]) + ) + ); + prop.value.properties + .filter(n => + (transformUtils.safeTraverse(n, ['key', 'name']) === webpackProp) + ) + .forEach( (externalProp) => { Object.keys(webpackProperties.externals[webpackProp]).forEach( (subProps) => { if(Array.isArray(webpackProperties.externals[webpackProp][subProps])) { - const subExternalArray = j.property( - 'init', - j.identifier(subProps), - j.arrayExpression([]) + const subExternalArray = transformUtils.createArrayWithChildren( + j, subProps, webpackProperties.externals[webpackProp][subProps], true ); - - webpackProperties.externals[webpackProp][subProps].forEach( (n) => { - return subExternalArray.value.elements.push(j.identifier(n)); - }); externalProp.value.properties.push(subExternalArray); } else { externalProp.value.properties.push( - j.property( - 'init', - j.identifier(subProps), - j.identifier( - webpackProperties.externals[webpackProp][subProps] + transformUtils.createPropertyWithSuppliedProperty( + j, + subProps, + transformUtils.createIdentifierOrLiteral( + j, webpackProperties.externals[webpackProp][subProps] ) ) ); } }); - } - }); - } + }); + } + }); }); - }); + } } if(webpackProperties['externals']) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 8c37b816f5b..68a2b5ce9b7 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -1,6 +1,6 @@ const webpackModuleTypes = require('./module-types'); const isAssignment = require('../../utils/is-assignment'); -const utils = require('./utils'); +const localUtils = require('./utils'); const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { @@ -8,65 +8,64 @@ module.exports = function(j, ast, yeomanConfig) { function createModuleProperties(p) { p.value.properties.push( - j.property('init', j.identifier('module'), j.objectExpression([])) + transformUtils.createPropertyWithSuppliedProperty(j, 'module', j.objectExpression([])) ); - let moduleNode = p.value.properties; - moduleNode.filter(n => n.key.name === 'module').forEach( (prop) => { - Object.keys(webpackProperties['module']).forEach( (webpackProp) => { + moduleNode.filter(n => + (transformUtils.safeTraverse(n, ['key', 'name']) === 'module') + ).forEach( (prop) => { + Object.keys(webpackProperties['module']) + .forEach( (webpackProp) => { if(['noParse', 'rules'].includes(webpackProp)) { if(webpackProperties.module[webpackProp].__paths) { // optional if user can't use regular regexp - utils.regExpStrategy(j, webpackProperties, webpackProp, prop); + localUtils.regExpStrategy(j, webpackProperties, webpackProp, prop); } else if(Array.isArray(webpackProperties.module[webpackProp])) { - const rulesArray = j.property( - 'init', - j.identifier(webpackProp), - j.arrayExpression([]) - ); + const rulesArray = transformUtils.createEmptyArrayProperty(j, webpackProp); prop.value.properties.push(rulesArray); // Keeps track of what object we're refering to when adding props let seen = -1; let rulesProperties = webpackProperties.module[webpackProp]; - rulesProperties.forEach( (subProps) => { - let rulesMatchProp = prop.value.properties.filter( - n => n.key.name === webpackProp + rulesProperties + .forEach( (subProps) => { + let rulesMatchProp = prop.value.properties.filter(n => + (transformUtils.safeTraverse(n, ['key', 'name']) === webpackProp) ); - rulesMatchProp.forEach( moduleProp => { for(let key in subProps) { if(key.indexOf('inject') >= 0) { - moduleProp.value.elements.push( subProps[key] ); - seen += 1; } - if(webpackModuleTypes.includes(key)) { if(key === 'test') { moduleProp.value.elements.push( j.objectExpression([]) ); seen += 1; - utils.createTestProperty(j, moduleProp, seen, key, subProps); + localUtils.createTestProperty( + j, moduleProp, seen, key, subProps + ); } if(key === 'enforce' || key === 'loader') { moduleProp.value.elements[seen].properties.push( - j.property( - 'init', - j.identifier(key), - j.identifier(subProps[key]) + transformUtils.createPropertyWithSuppliedProperty( + j, + key, + transformUtils.createIdentifierOrLiteral( + j, subProps[key] + ) ) ); } if(key === 'options' || key === 'use') { const subProperties = (key === 'use') ? - utils.createUseProperties(j, key, subProps) : - utils.createOption(j, subProps, key); + localUtils.createUseProperties(j, key, subProps) : + localUtils.createOption(j, subProps, key); moduleProp.value.elements[seen].properties.push( subProperties ); @@ -98,11 +97,7 @@ module.exports = function(j, ast, yeomanConfig) { } // module.rules is an external object return prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - pushProperty - ) + transformUtils.createPropertyWithSuppliedProperty(j, webpackProp, pushProperty) ); } } diff --git a/lib/creator/transformations/module/utils.js b/lib/creator/transformations/module/utils.js index 71682afa9b6..299c50758c6 100644 --- a/lib/creator/transformations/module/utils.js +++ b/lib/creator/transformations/module/utils.js @@ -4,20 +4,14 @@ const transformUtils = require('../../../transformations/utils'); function regExpStrategy(j, webpackProperties, webpackProp, prop) { let RegExpDec = webpackProperties.module[webpackProp].__paths[0].value.program.body[0].expression; prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(RegExpDec.value)) + transformUtils.createPropertyWithSuppliedProperty(j, webpackProp, j.literal(RegExpDec.value)) ); } // Module.rules.myRule.test function createTestProperty(j, moduleProp, seen, key, subProps) { moduleProp.value.elements[seen].properties.push( - j.property( - 'init', - j.identifier(key), - j.literal( - subProps[key] - ) - ) + transformUtils.createPropertyWithSuppliedProperty(j, key, j.literal(subProps[key])) ); } // Module.rules.myRule.option @@ -59,30 +53,36 @@ function createUseProperties(j, key, subProps) { Object.keys(subProps[key]).forEach( (optionProperty) => { if(typeof(subProps[key][optionProperty]) === 'string') { useVal.value.elements.push( - j.identifier(subProps[key][optionProperty]) + transformUtils.createIdentifierOrLiteral(subProps[key][optionProperty]) ); } else { let loaderProperty = j.objectExpression([]); Object.keys(subProps[key][optionProperty]).forEach( subOptionProp => { if(typeof(subProps[key][optionProperty][subOptionProp]) === 'string') { loaderProperty.properties.push( - j.property('init', - j.identifier(subOptionProp), - j.identifier(subProps[key][optionProperty][subOptionProp]) - )); + transformUtils.createPropertyWithSuppliedProperty( + j, + subOptionProp, + transformUtils.createIdentifierOrLiteral( + j, subProps[key][optionProperty][subOptionProp] + ) + ) + ); } else { let subSubProps = j.objectExpression([]); Object.keys(subProps[key][optionProperty][subOptionProp]).forEach( (underlyingOption) => { subSubProps.properties.push( - j.property('init', - j.identifier(underlyingOption), - j.identifier( - subProps[key][optionProperty][subOptionProp][underlyingOption] - )) + transformUtils.createPropertyWithSuppliedProperty( + j, + underlyingOption, + transformUtils.createIdentifierOrLiteral( + j, subProps[key][optionProperty][subOptionProp][underlyingOption] + ) + ) ); }); loaderProperty.properties.push( - j.property('init', j.identifier(subOptionProp), subSubProps) + transformUtils.createPropertyWithSuppliedProperty(j, subOptionProp, subSubProps) ); } }); diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index bdc7bff0f75..f1bb5fb23e2 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -4,16 +4,28 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createNodeProperty(p) { - const nodeVal = webpackProperties['node']; - const propVal = j.objectExpression( - Object.keys(nodeVal).map(prop => { - return j.property('init', j.identifier(prop), - transformUtils.createIdentifierOrLiteral(j, nodeVal[prop])); - }) + let node = p.value.properties; + node.push( + transformUtils.createPropertyWithSuppliedProperty(j, 'node', j.objectExpression([])) ); - transformUtils.checkIfExistsAndAddValue(j, p, 'node', propVal); + node.filter(n => + (transformUtils.safeTraverse(n, ['key', 'name']) === 'node') + ).forEach( (prop) => { + Object.keys(webpackProperties.node).forEach( (webpackProp) => { + prop.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty( + j, + webpackProp, + transformUtils.createIdentifierOrLiteral( + j, + webpackProperties.node[webpackProp] + ) + ) + ); + }); + }); } - if(webpackProperties['node'] && typeof(webpackProperties['node']) === 'object') { + if(webpackProperties['node']) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(p, createNodeProperty)); } else { diff --git a/lib/creator/transformations/other/__snapshots__/others.test.js.snap b/lib/creator/transformations/other/__snapshots__/others.test.js.snap index 5b2dcaf01df..da78db4d508 100644 --- a/lib/creator/transformations/other/__snapshots__/others.test.js.snap +++ b/lib/creator/transformations/other/__snapshots__/others.test.js.snap @@ -39,6 +39,18 @@ exports[`cache transforms correctly using "others-0" data 1`] = ` " `; +exports[`cache transforms correctly using "others-0" data 2`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + cache: cacheVal +} +" +`; + exports[`profile transforms correctly using "others-0" data 1`] = ` "module.exports = { entry: 'index.js', diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index 91f8f430d80..b7246efd06f 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -4,15 +4,28 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createAMDProperty(p) { - const amd = webpackProperties['amd']; - const propVal = j.objectExpression( - Object.keys(amd).map(prop => { - return j.property('init', j.identifier(prop), - transformUtils.createIdentifierOrLiteral(j, amd[prop]) - ); - }) + let amdNode = p.value.properties; + amdNode.push( + transformUtils.createPropertyWithSuppliedProperty( + j, 'amd', j.objectExpression([]) + ) ); - transformUtils.checkIfExistsAndAddValue(j, p, 'amd', propVal); + amdNode.filter(n => + (transformUtils.safeTraverse(n, ['key', 'name']) === 'amd') + ).forEach( (prop) => { + Object.keys(webpackProperties['amd']).forEach( (webpackProp) => { + prop.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty( + j, + webpackProp, + transformUtils.createIdentifierOrLiteral( + j, + webpackProperties.amd[webpackProp] + ) + ) + ); + }); + }); } if(webpackProperties['amd'] && typeof(webpackProperties['amd']) === 'object') { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index d7c72dc025c..c63cc66fb53 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -5,8 +5,11 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createBailProperty(p) { - let propVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['bail']); - transformUtils.checkIfExistsAndAddValue(j, p, 'bail', propVal); + let bailVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['bail']); + + return p.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty(j, 'bail', bailVal) + ); } if(webpackProperties['bail']) { diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index 4a3b6ed0d15..a298ccbfe88 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -4,8 +4,11 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createCacheProperty(p) { - let propVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['cache']); - transformUtils.checkIfExistsAndAddValue(j, p, 'cache', propVal); + let cacheVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['cache']); + + return p.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty(j, 'cache', cacheVal) + ); } if(webpackProperties['cache']) { diff --git a/lib/creator/transformations/other/others.test.js b/lib/creator/transformations/other/others.test.js index 53326e09002..477c89cc2de 100644 --- a/lib/creator/transformations/other/others.test.js +++ b/lib/creator/transformations/other/others.test.js @@ -6,4 +6,5 @@ defineTest(__dirname, 'amd', 'others-0', {amd : { }); defineTest(__dirname, 'bail', 'others-0', {bail : true}); defineTest(__dirname, 'cache', 'others-0', {cache : true}); +defineTest(__dirname, 'cache', 'others-0', {cache : 'cacheVal'}); defineTest(__dirname, 'profile', 'others-0', {profile : true}); diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index abb362e0b3a..f6f2f0170e3 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -4,8 +4,11 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createProfileProperty(p) { - let propVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['profile']); - transformUtils.checkIfExistsAndAddValue(j, p, 'profile', propVal); + let profileVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['profile']); + + return p.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty(j, 'profile', profileVal) + ); } if(webpackProperties['profile']) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index d1cdcdb8e57..da2ed118f86 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -1,25 +1,25 @@ const webpackOutputTypes = require('./output-types'); const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createOutputProperties(p) { let outputNode = p.value.properties; - outputNode.push(j.property('init', j.identifier('output'), j.objectExpression([]))); + outputNode.push( + transformUtils.createPropertyWithSuppliedProperty( + j, + 'output', + j.objectExpression([]) + ) + ); - outputNode.filter( n => n.key.name === 'output').forEach( (prop) => { + outputNode.filter( n => + (transformUtils.safeTraverse(n, ['key', 'name']) === 'output') + ).forEach( (prop) => { Object.keys(webpackProperties.output).forEach( (webpackProp) => { if(webpackOutputTypes.includes(webpackProp)) { - if(typeof webpackProperties.output[webpackProp] === 'boolean') { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.literal(webpackProperties.output[webpackProp]) - ) - ); - } - else if(webpackProperties.output[webpackProp].__paths) { + if(webpackProperties.output[webpackProp].__paths) { let regExpProp = webpackProperties.output[webpackProp].__paths[0].value.program.body[0].expression; @@ -29,10 +29,13 @@ module.exports = function(j, ast, yeomanConfig) { } else { prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.identifier(webpackProperties.output[webpackProp]) + transformUtils.createPropertyWithSuppliedProperty( + j, + webpackProp, + transformUtils.createIdentifierOrLiteral( + j, + webpackProperties.output[webpackProp] + ) ) ); } diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 5b403f1a15f..85a9011a87a 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -1,37 +1,32 @@ const performanceTypes = require('./performance-types'); const isAssignment = require('../../utils/is-assignment'); +const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createPerformanceProperty(p) { let performanceNode = p.value.properties; - performanceNode.push(j.property('init', j.identifier('performance'), j.objectExpression([]))); - performanceNode.filter(n => n.key.name === 'performance').forEach( (prop) => { + performanceNode.push( + transformUtils.createPropertyWithSuppliedProperty( + j, 'performance', j.objectExpression([]) + ) + ); + performanceNode.filter(n => + (transformUtils.safeTraverse(n, ['key', 'name']) === 'performance') + ).forEach( (prop) => { Object.keys(webpackProperties.performance).forEach( (webpackProp) => { if(performanceTypes.includes(webpackProp)) { - if(Array.isArray(webpackProperties.performance[webpackProp])) { - throw new Error('Unknown Property', webpackProp); - } - else { - if(typeof(webpackProperties.performance[webpackProp]) == 'string') { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.identifier(webpackProperties.performance[webpackProp]) - ) - ); - } else { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.literal(webpackProperties.performance[webpackProp]) - ) - ); - } - } + prop.value.properties.push( + transformUtils.createPropertyWithSuppliedProperty( + j, + webpackProp, + transformUtils.createIdentifierOrLiteral( + j, + webpackProperties.performance[webpackProp] + ) + ) + ); } }); }); diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index 60926d2b653..5fdc5dc7dc9 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -4,13 +4,8 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createPluginsProperty(p) { - const plugins = webpackProperties['plugins']; - const propVal = j.arrayExpression( - Object.keys(plugins).map(plugin => { - return j.identifier(plugins[plugin]); - }) - ); - transformUtils.checkIfExistsAndAddValue(j, p, 'plugins', propVal); + const pluginArray = transformUtils.createArrayWithChildren(j, 'plugins', webpackProperties); + return p.value.properties.push(pluginArray); } if(webpackProperties['plugins'] && Array.isArray(webpackProperties['plugins'])) { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createPluginsProperty)); From 107d37c2982272e36a62039faf9b3df868da111c Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 22 Apr 2017 16:33:41 +0200 Subject: [PATCH 061/101] utils: add regex util --- lib/creator/transformations/module/utils.js | 4 ++-- lib/creator/transformations/output/output.js | 5 ++--- lib/transformations/utils.js | 17 +++++++++++++++-- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/lib/creator/transformations/module/utils.js b/lib/creator/transformations/module/utils.js index 299c50758c6..2650f6297b4 100644 --- a/lib/creator/transformations/module/utils.js +++ b/lib/creator/transformations/module/utils.js @@ -2,9 +2,9 @@ const transformUtils = require('../../../transformations/utils'); // optional for the user to parse using jscodeshift for only this if a regular regexp doesnt work. function regExpStrategy(j, webpackProperties, webpackProp, prop) { - let RegExpDec = webpackProperties.module[webpackProp].__paths[0].value.program.body[0].expression; + let RegExpDec = transformUtils.createExternalRegExp(j, webpackProperties.module[webpackProp]); prop.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty(j, webpackProp, j.literal(RegExpDec.value)) + transformUtils.createPropertyWithSuppliedProperty(j, webpackProp, RegExpDec) ); } diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index da2ed118f86..ad332169bed 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -20,11 +20,10 @@ module.exports = function(j, ast, yeomanConfig) { Object.keys(webpackProperties.output).forEach( (webpackProp) => { if(webpackOutputTypes.includes(webpackProp)) { if(webpackProperties.output[webpackProp].__paths) { - let regExpProp = - webpackProperties.output[webpackProp].__paths[0].value.program.body[0].expression; + let regExpProp = transformUtils.createExternalRegExp(j, webpackProperties.output[webpackProp]); prop.value.properties.push( - j.property('init', j.identifier(webpackProp), j.literal(regExpProp.value)) + j.property('init', j.identifier(webpackProp), regExpProp) ); } else { diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index ef47cd336e3..09b6968e48f 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -350,10 +350,22 @@ function createArrayWithChildren(j, key, subProps, shouldDropKeys) { * @returns - { Node } - An property with the supplied property */ -function createPropertyWithSuppliedProperty(j,key, prop) { +function createPropertyWithSuppliedProperty(j, key, prop) { return j.property('init', j.identifier(key), prop); } +/* +* @function createExternalRegExp +* +* Finds a regexp property with an already parsed AST from the user +* @param j — jscodeshift API +* @param { String } prop - property to find the value at +* @returns - { Node } - A literal node with the found regexp +*/ +function createExternalRegExp(j, prop) { + let regExpProp = prop.__paths[0].value.program.body[0].expression; + return j.literal(regExpProp.value); +} module.exports = { safeTraverse, @@ -370,5 +382,6 @@ module.exports = { checkIfExistsAndAddValue, createArrayWithChildren, createEmptyArrayProperty, - createPropertyWithSuppliedProperty + createPropertyWithSuppliedProperty, + createExternalRegExp }; From b7a92268911369e9294cf1ab641f644203f3c4fb Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 22 Apr 2017 16:59:59 +0200 Subject: [PATCH 062/101] chore: add JSdocs to each transform --- .../transformations/context/context.js | 12 +++++ .../transformations/devtool/devtool.js | 12 +++++ lib/creator/transformations/entry/entry.js | 13 +++++ .../transformations/externals/externals.js | 12 +++++ lib/creator/transformations/index.js | 3 +- lib/creator/transformations/module/module.js | 12 +++++ lib/creator/transformations/node/node.js | 12 +++++ lib/creator/transformations/other/amd.js | 12 +++++ lib/creator/transformations/other/bail.js | 12 +++++ lib/creator/transformations/other/cache.js | 12 +++++ lib/creator/transformations/other/merge.js | 12 +++++ lib/creator/transformations/other/profile.js | 12 +++++ lib/creator/transformations/output/output.js | 12 +++++ .../performance/performance.js | 12 +++++ .../transformations/plugins/plugins.js | 11 +++++ .../transformations/resolve/resolve.js | 11 +++++ lib/creator/transformations/stats/stats.js | 11 +++++ .../target/__snapshots__/target.test.js.snap | 9 ++-- .../target/__testfixtures__/target-1.input.js | 3 +- lib/creator/transformations/target/target.js | 17 +++++-- .../transformations/target/target.test.js | 4 +- .../transformations/top-scope/top-scope.js | 12 +++++ .../watch/__snapshots__/watch.test.js.snap | 16 +++---- .../__snapshots__/watchOptions.test.js.snap | 16 +++---- .../watch/__testfixtures__/watch-1.input.js | 4 +- .../watch/__testfixtures__/watch-2.input.js | 4 -- lib/creator/transformations/watch/watch.js | 19 ++++++-- .../transformations/watch/watchOptions.js | 47 ++++++++++++++----- lib/creator/yeoman/webpack-adapter.js | 8 +++- 29 files changed, 300 insertions(+), 52 deletions(-) diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index b5a26b516b6..b0fe8cbb227 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,6 +1,18 @@ const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for context. Finds the context property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index faed2a22ab8..1e8a9ac98ba 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,6 +1,18 @@ const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for devtool. Finds the devtool property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index bc95f986cf0..a9da5ac6e3d 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,6 +1,19 @@ const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for entry. Finds the entry property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index b78fffbbca5..9b0ed6d71ae 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -1,5 +1,17 @@ const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for externals. Finds the externals property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createExternalProperty(p) { diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 36660510f7b..e0cee855322 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -33,7 +33,8 @@ const topScopeTransform = require('./top-scope/top-scope'); * Runs the transformations from an object we get from yeoman * * @param { Object } transformObject - Options to transform -* @returns { } TODO +* @returns { } - A promise that writes each transform, runs prettier +* and writes the file */ const transformsObject = { diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 68a2b5ce9b7..13a52e65de7 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -3,6 +3,18 @@ const isAssignment = require('../../utils/is-assignment'); const localUtils = require('./utils'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for module. Finds the module property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index f1bb5fb23e2..f596c4140f0 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -1,6 +1,18 @@ const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for node. Finds the node property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createNodeProperty(p) { diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index b7246efd06f..1b5bfd116b5 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -1,6 +1,18 @@ const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for amd. Finds the amd property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createAMDProperty(p) { diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index c63cc66fb53..e1cee49eca6 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,6 +1,18 @@ const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for bail. Finds the bail property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index a298ccbfe88..f049f49843c 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,6 +1,18 @@ const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for cache. Finds the cache property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createCacheProperty(p) { diff --git a/lib/creator/transformations/other/merge.js b/lib/creator/transformations/other/merge.js index 59b404e5ace..fc03000158d 100644 --- a/lib/creator/transformations/other/merge.js +++ b/lib/creator/transformations/other/merge.js @@ -1,5 +1,17 @@ const isAssignment = require('../../utils/is-assignment'); + +/* +* +* Transform for merge. Finds the merge property from yeoman and creates a way +* for users to allow webpack-merge in their scaffold +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createMergeProperty(p) { diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index f6f2f0170e3..a9f661f0768 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,6 +1,18 @@ const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for profile. Finds the profile property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createProfileProperty(p) { diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index ad332169bed..43b95aab4ed 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -2,6 +2,18 @@ const webpackOutputTypes = require('./output-types'); const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for output. Finds the output property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createOutputProperties(p) { diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 85a9011a87a..ca15babcf8b 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -2,6 +2,18 @@ const performanceTypes = require('./performance-types'); const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for performance. Finds the performance property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index 5fdc5dc7dc9..33498838924 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -1,6 +1,17 @@ const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); +/* +* +* Transform for plugins. Finds the plugins property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createPluginsProperty(p) { diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index 9e1e7cc964e..a8d5d41f893 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -1,6 +1,17 @@ const resolveTypes = require('./resolve-types'); const isAssignment = require('../../utils/is-assignment'); +/* +* +* Transform for resolve. Finds the resolve property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createResolveProperties(p) { diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index d09b23bc0bf..a74013afac1 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -2,6 +2,17 @@ const statsTypes = require('./stats-types'); const isAssignment = require('../../utils/is-assignment'); const transformUtils = require('../../../transformations/utils'); +/* +* +* Transform for stats. Finds the stats property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createStatsProperty(p) { diff --git a/lib/creator/transformations/target/__snapshots__/target.test.js.snap b/lib/creator/transformations/target/__snapshots__/target.test.js.snap index 63d87b56960..3af819e1ce2 100644 --- a/lib/creator/transformations/target/__snapshots__/target.test.js.snap +++ b/lib/creator/transformations/target/__snapshots__/target.test.js.snap @@ -7,18 +7,19 @@ exports[`target transforms correctly using "target-0" data 1`] = ` filename: 'bundle.js' }, - target: async-node + target: 'async-node' } " `; exports[`target transforms correctly using "target-1" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - target: async-node + + target: node } " `; diff --git a/lib/creator/transformations/target/__testfixtures__/target-1.input.js b/lib/creator/transformations/target/__testfixtures__/target-1.input.js index c8e83f95936..ea0822c2484 100644 --- a/lib/creator/transformations/target/__testfixtures__/target-1.input.js +++ b/lib/creator/transformations/target/__testfixtures__/target-1.input.js @@ -2,6 +2,5 @@ module.exports = { entry: 'index.js', output: { filename: 'bundle.js' - }, - target: 'node' + } } diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index ef4b5393768..35bd81b320e 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,11 +1,22 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for target. Finds the target property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createTargetProperty(p) { - const propValue = transformUtils.createIdentifierOrLiteral(j, webpackProperties['target']); - transformUtils.checkIfExistsAndAddValue(j, p, 'target', propValue); + return p.value.properties.push( + j.property('init', j.identifier('target'), j.identifier(webpackProperties['target'])) + ); } if(webpackProperties['target'] && webpackProperties['target'].length) { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createTargetProperty)); diff --git a/lib/creator/transformations/target/target.test.js b/lib/creator/transformations/target/target.test.js index f8760bb98dd..a91ea010dda 100644 --- a/lib/creator/transformations/target/target.test.js +++ b/lib/creator/transformations/target/target.test.js @@ -1,4 +1,4 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'target', 'target-0', {target : 'async-node'}); -defineTest(__dirname, 'target', 'target-1', {target : 'async-node'}); +defineTest(__dirname, 'target', 'target-0', {target : '\'async-node\''}); +defineTest(__dirname, 'target', 'target-1', {target : 'node'}); diff --git a/lib/creator/transformations/top-scope/top-scope.js b/lib/creator/transformations/top-scope/top-scope.js index c1b3b931ffc..46d438a2320 100644 --- a/lib/creator/transformations/top-scope/top-scope.js +++ b/lib/creator/transformations/top-scope/top-scope.js @@ -1,3 +1,15 @@ + +/* +* +* Get an property named topScope from yeoman and inject it to the top scope of +* the config, outside module.exports +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing topscope properties +* @returns ast - jscodeshift API +*/ + module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.topScope; function createTopScopeProperty(p) { diff --git a/lib/creator/transformations/watch/__snapshots__/watch.test.js.snap b/lib/creator/transformations/watch/__snapshots__/watch.test.js.snap index 70131f1c10c..964ece52812 100644 --- a/lib/creator/transformations/watch/__snapshots__/watch.test.js.snap +++ b/lib/creator/transformations/watch/__snapshots__/watch.test.js.snap @@ -26,24 +26,24 @@ exports[`watch transforms correctly using "watch-0" data 2`] = ` exports[`watch transforms correctly using "watch-1" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - watch: true, - watchOptions: {} + + watch: true } " `; exports[`watch transforms correctly using "watch-1" data 2`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - watch: false, - watchOptions: {} + + watch: false } " `; diff --git a/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap b/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap index cf7976733c0..6f93736f0fd 100644 --- a/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap +++ b/lib/creator/transformations/watch/__snapshots__/watchOptions.test.js.snap @@ -18,12 +18,12 @@ exports[`watchOptions transforms correctly using "watch-0" data 1`] = ` exports[`watchOptions transforms correctly using "watch-1" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - watch: false, - watchOptions: { + + watchOptions: { aggregateTimeout: 300, poll: 1000, ignored: /node_modules/ @@ -34,12 +34,12 @@ exports[`watchOptions transforms correctly using "watch-1" data 1`] = ` exports[`watchOptions transforms correctly using "watch-2" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - watch: false, - watchOptions: { + + watchOptions: { aggregateTimeout: 300, poll: 1000, ignored: /node_modules/ diff --git a/lib/creator/transformations/watch/__testfixtures__/watch-1.input.js b/lib/creator/transformations/watch/__testfixtures__/watch-1.input.js index 503bb1d4a71..ea0822c2484 100644 --- a/lib/creator/transformations/watch/__testfixtures__/watch-1.input.js +++ b/lib/creator/transformations/watch/__testfixtures__/watch-1.input.js @@ -2,7 +2,5 @@ module.exports = { entry: 'index.js', output: { filename: 'bundle.js' - }, - watch: false, - watchOptions: {} + } } diff --git a/lib/creator/transformations/watch/__testfixtures__/watch-2.input.js b/lib/creator/transformations/watch/__testfixtures__/watch-2.input.js index 1d94f02f15f..ea0822c2484 100644 --- a/lib/creator/transformations/watch/__testfixtures__/watch-2.input.js +++ b/lib/creator/transformations/watch/__testfixtures__/watch-2.input.js @@ -2,9 +2,5 @@ module.exports = { entry: 'index.js', output: { filename: 'bundle.js' - }, - watch: false, - watchOptions: { - aggregateTimeout: 320 } } diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 188b34f59cf..79cafe6d69c 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,11 +1,22 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for watch. Finds the watch property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchProperty(p) { - const propValue = transformUtils.createIdentifierOrLiteral(j, webpackProperties['watch']); - transformUtils.checkIfExistsAndAddValue(j, p, 'watch', propValue); + return p.value.properties.push( + j.property('init', j.identifier('watch'), j.literal(webpackProperties['watch'])) + ); } if(typeof(webpackProperties['watch']) === 'boolean') { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchProperty)); @@ -13,5 +24,3 @@ module.exports = function(j, ast, yeomanConfig) { return ast; } }; - - diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index 8f9ee9331ee..6c95b365523 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -1,22 +1,47 @@ const watchOptionTypes = require('./watchOptions-types'); const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); + +/* +* +* Transform for watchOptions. Finds the watchOptions property from yeoman and creates a +* property based on what the user has given us. +* +* @param j — jscodeshift API +* @param ast - jscodeshift API +* @param { Object } yeomanConfig - Object containing transformation rules +* @returns ast - jscodeshift API +*/ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchOptionsProperty(p) { - const watchOptions = webpackProperties['watchOptions']; - const propValue = j.objectExpression( - Object.keys(watchOptions).map(option => { - if (watchOptionTypes.includes(option)) { - return j.property('init', j.identifier(option), - transformUtils.createIdentifierOrLiteral(j, watchOptions[option])); + let watchOptionsNode = p.value.properties; + watchOptionsNode.push(j.property('init', j.identifier('watchOptions'), j.objectExpression([]))); + watchOptionsNode.filter(n => n.key.name === 'watchOptions').forEach( (prop) => { + Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { + if(watchOptionTypes.includes(watchOption)) { + if(typeof(webpackProperties['watchOptions'][watchOption]) === 'number') { + prop.value.properties.push( + j.property( + 'init', + j.identifier(watchOption), + j.literal(webpackProperties['watchOptions'][watchOption]) + ) + ); + } else { + prop.value.properties.push( + j.property( + 'init', + j.identifier(watchOption), + j.identifier(webpackProperties['watchOptions'][watchOption]) + ) + ); + } } else { - throw new Error('Unknown Property', option); + throw new Error('Unknown Property', watchOption); } - }) - ); - transformUtils.checkIfExistsAndAddValue(j, p, 'watchOptions', propValue); + }); + }); } if(webpackProperties['watchOptions'] && webpackProperties['watchOptions']) { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchOptionsProperty)); diff --git a/lib/creator/yeoman/webpack-adapter.js b/lib/creator/yeoman/webpack-adapter.js index ae95fc287eb..00cf84195c1 100644 --- a/lib/creator/yeoman/webpack-adapter.js +++ b/lib/creator/yeoman/webpack-adapter.js @@ -1,6 +1,12 @@ const inquirer = require('inquirer'); -// we can use rxJS here to validate the answers against a generator +/* +* @class - WebpackAdapter +* +* Custom adapter that is integrated in the scaffold. Here we can validate +* paths and answers from the user +* +*/ module.exports = class WebpackAdapter { prompt(questions, callback) { const promise = inquirer.prompt(questions); From 9859b03be8f27fce16769c2d875855848844b3c8 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 22 Apr 2017 23:07:38 +0200 Subject: [PATCH 063/101] enhancements: use more utility on transforms --- .../transformations/context/context.js | 8 +-- .../__snapshots__/devtool.test.js.snap | 14 +++-- .../__testfixtures__/devtool-1.input.js | 3 +- .../transformations/devtool/devtool.js | 5 +- .../transformations/externals/externals.js | 62 ++++++------------- lib/creator/transformations/module/module.js | 29 +++------ lib/creator/transformations/module/utils.js | 42 +++++-------- lib/transformations/utils.js | 27 +++++++- 8 files changed, 83 insertions(+), 107 deletions(-) diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index b0fe8cbb227..2f8179f3830 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -17,11 +17,7 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createContextProperty(p) { - return p.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, 'context', j.identifier(webpackProperties['context']) - ) - ); + return utils.pushCreateProperty(j, p, 'context', webpackProperties['context']); } if(webpackProperties['context']) { diff --git a/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap index b1835ac1085..d343b1fc107 100644 --- a/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap +++ b/lib/creator/transformations/devtool/__snapshots__/devtool.test.js.snap @@ -26,22 +26,24 @@ exports[`devtool transforms correctly using "devtool-0" data 2`] = ` exports[`devtool transforms correctly using "devtool-1" data 1`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - devtool: 'cheap-module-source-map' + + devtool: 'cheap-module-source-map' } " `; exports[`devtool transforms correctly using "devtool-1" data 2`] = ` "module.exports = { - entry: 'index.js', - output: { + entry: 'index.js', + output: { filename: 'bundle.js' }, - devtool: false + + devtool: false } " `; diff --git a/lib/creator/transformations/devtool/__testfixtures__/devtool-1.input.js b/lib/creator/transformations/devtool/__testfixtures__/devtool-1.input.js index d7fc037f215..ea0822c2484 100644 --- a/lib/creator/transformations/devtool/__testfixtures__/devtool-1.input.js +++ b/lib/creator/transformations/devtool/__testfixtures__/devtool-1.input.js @@ -2,6 +2,5 @@ module.exports = { entry: 'index.js', output: { filename: 'bundle.js' - }, - devtool: 'eval' + } } diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index 1e8a9ac98ba..23067e42422 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -17,8 +17,7 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createDevToolProperty(p) { - const propValue = transformUtils.createIdentifierOrLiteral(j, webpackProperties['devtool']); - return transformUtils.checkIfExistsAndAddValue(j, p, 'devtool', propValue); + return utils.pushCreateProperty(j, p, 'devtool', webpackProperties['devtool']); } if(webpackProperties['devtool']) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 9b0ed6d71ae..7e2a026e2d4 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -1,4 +1,4 @@ -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -16,91 +16,65 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createExternalProperty(p) { if(webpackProperties.externals instanceof RegExp || typeof(webpackProperties.externals) === 'string') { - let stringProp = webpackProperties.externals instanceof RegExp ? - j.literal(webpackProperties.externals) : - transformUtils.createIdentifierOrLiteral(j, webpackProperties.externals); - - return p.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, 'externals', stringProp - ) - ); + return utils.pushCreateProperty(j, p, 'externals', webpackProperties.externals); } else if(Array.isArray(webpackProperties.externals)) { - const externalArray = transformUtils.createEmptyArrayProperty(j, 'externals'); + const externalArray = utils.createEmptyArrayProperty(j, 'externals'); webpackProperties.externals.forEach( (n) => { // [{myprop: 'hello'}] let objectOfArray = j.objectExpression([]); if(typeof(n) !== 'string') { for(let key in n) { objectOfArray.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, key, transformUtils.createIdentifierOrLiteral(j, n[key])) + utils.createPropertyWithSuppliedProperty( + j, key, utils.createIdentifierOrLiteral(j, n[key])) ); } externalArray.value.elements.push(objectOfArray); } else { // [val] - return externalArray.value.elements.push(transformUtils.createIdentifierOrLiteral(j, n)); + return externalArray.value.elements.push(utils.createIdentifierOrLiteral(j, n)); } }); return p.value.properties.push(externalArray); } else { - p.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, 'externals', j.objectExpression([]) - ) - ); + utils.pushCreateProperty(j, p, 'externals', j.objectExpression([])); let externalsProp = p.value.properties; externalsProp.filter(n => - (transformUtils.safeTraverse(n, ['key', 'name']) === 'externals') + (utils.safeTraverse(n, ['key', 'name']) === 'externals') ).forEach( (prop) => { Object.keys(webpackProperties['externals']).forEach( (webpackProp) => { if(Array.isArray(webpackProperties.externals[webpackProp])) { // if we got a type, we make it an array - const externalArray = transformUtils.createArrayWithChildren( + const externalArray = utils.createArrayWithChildren( j, webpackProp, webpackProperties.externals[webpackProp], true ); prop.value.properties.push(externalArray); } else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { - prop.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, - webpackProp, - transformUtils.createIdentifierOrLiteral( - j, webpackProperties.externals[webpackProp] - ) - ) + utils.pushCreateProperty( + j, prop, webpackProp, webpackProperties.externals[webpackProp] ); } else { - prop.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, webpackProp, j.objectExpression([]) - ) + utils.pushCreateProperty( + j, prop, webpackProp, j.objectExpression([]) ); prop.value.properties .filter(n => - (transformUtils.safeTraverse(n, ['key', 'name']) === webpackProp) + (utils.safeTraverse(n, ['key', 'name']) === webpackProp) ) .forEach( (externalProp) => { Object.keys(webpackProperties.externals[webpackProp]).forEach( (subProps) => { if(Array.isArray(webpackProperties.externals[webpackProp][subProps])) { - const subExternalArray = transformUtils.createArrayWithChildren( + const subExternalArray = utils.createArrayWithChildren( j, subProps, webpackProperties.externals[webpackProp][subProps], true ); externalProp.value.properties.push(subExternalArray); } else { - externalProp.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, - subProps, - transformUtils.createIdentifierOrLiteral( - j, webpackProperties.externals[webpackProp][subProps] - ) - ) + utils.pushCreateProperty( + j, externalProp, subProps, webpackProperties.externals[webpackProp][subProps] ); } }); @@ -112,7 +86,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['externals']) { return ast.find(j.ObjectExpression) - .filter(p => transformUtils.safeTraverse(p , ['parent', 'value', 'left', 'property', 'name']) === 'exports') + .filter(p => utils.safeTraverse(p , ['parent', 'value', 'left', 'property', 'name']) === 'exports') .forEach(createExternalProperty); } else { return ast; diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 13a52e65de7..1c800e0fdca 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -1,7 +1,7 @@ const webpackModuleTypes = require('./module-types'); const isAssignment = require('../../utils/is-assignment'); const localUtils = require('./utils'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -19,12 +19,10 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createModuleProperties(p) { - p.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty(j, 'module', j.objectExpression([])) - ); + utils.pushCreateProperty(j, p, 'module', j.objectExpression([])); let moduleNode = p.value.properties; moduleNode.filter(n => - (transformUtils.safeTraverse(n, ['key', 'name']) === 'module') + (utils.safeTraverse(n, ['key', 'name']) === 'module') ).forEach( (prop) => { Object.keys(webpackProperties['module']) .forEach( (webpackProp) => { @@ -34,7 +32,7 @@ module.exports = function(j, ast, yeomanConfig) { localUtils.regExpStrategy(j, webpackProperties, webpackProp, prop); } else if(Array.isArray(webpackProperties.module[webpackProp])) { - const rulesArray = transformUtils.createEmptyArrayProperty(j, webpackProp); + const rulesArray = utils.createEmptyArrayProperty(j, webpackProp); prop.value.properties.push(rulesArray); // Keeps track of what object we're refering to when adding props let seen = -1; @@ -43,7 +41,7 @@ module.exports = function(j, ast, yeomanConfig) { rulesProperties .forEach( (subProps) => { let rulesMatchProp = prop.value.properties.filter(n => - (transformUtils.safeTraverse(n, ['key', 'name']) === webpackProp) + (utils.safeTraverse(n, ['key', 'name']) === webpackProp) ); rulesMatchProp.forEach( moduleProp => { for(let key in subProps) { @@ -65,10 +63,10 @@ module.exports = function(j, ast, yeomanConfig) { } if(key === 'enforce' || key === 'loader') { moduleProp.value.elements[seen].properties.push( - transformUtils.createPropertyWithSuppliedProperty( + utils.createPropertyWithSuppliedProperty( j, key, - transformUtils.createIdentifierOrLiteral( + utils.createIdentifierOrLiteral( j, subProps[key] ) ) @@ -93,7 +91,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(key === 'include' || key === 'exclude') { moduleProp.value.elements[seen].properties.push( - transformUtils.createArrayWithChildren(j, key, subProps) + utils.createArrayWithChildren(j, key, subProps) ); } } @@ -101,15 +99,8 @@ module.exports = function(j, ast, yeomanConfig) { }); }); } else { - let pushProperty; - if(webpackProp === 'noParse') { - pushProperty = j.literal(webpackProperties.module[webpackProp]); - } else { - pushProperty = j.identifier(webpackProperties.module[webpackProp]); - } - // module.rules is an external object - return prop.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty(j, webpackProp, pushProperty) + return utils.pushCreateProperty( + j, prop, webpackProp, webpackProperties.module[webpackProp] ); } } diff --git a/lib/creator/transformations/module/utils.js b/lib/creator/transformations/module/utils.js index 2650f6297b4..58865e8b171 100644 --- a/lib/creator/transformations/module/utils.js +++ b/lib/creator/transformations/module/utils.js @@ -1,17 +1,15 @@ -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); // optional for the user to parse using jscodeshift for only this if a regular regexp doesnt work. function regExpStrategy(j, webpackProperties, webpackProp, prop) { - let RegExpDec = transformUtils.createExternalRegExp(j, webpackProperties.module[webpackProp]); - prop.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty(j, webpackProp, RegExpDec) - ); + let RegExpDec = utils.createExternalRegExp(j, webpackProperties.module[webpackProp]); + return utils.pushCreateProperty(j, prop, webpackProp, RegExpDec); } // Module.rules.myRule.test function createTestProperty(j, moduleProp, seen, key, subProps) { moduleProp.value.elements[seen].properties.push( - transformUtils.createPropertyWithSuppliedProperty(j, key, j.literal(subProps[key])) + utils.createPropertyWithSuppliedProperty(j, key, j.literal(subProps[key])) ); } // Module.rules.myRule.option @@ -20,27 +18,19 @@ function createOption(j, subProps, key) { let optionProp; if(typeof(subProps[key]) === 'string') { - optionProp = transformUtils.createIdentifierOrLiteral(j, subProps[key]); - optionVal = transformUtils.createPropertyWithSuppliedProperty(j, key, optionProp); + optionProp = utils.createIdentifierOrLiteral(j, subProps[key]); + optionVal = utils.createPropertyWithSuppliedProperty(j, key, optionProp); } else { - optionVal = transformUtils.createPropertyWithSuppliedProperty(j, key, j.objectExpression([])); + optionVal = utils.createPropertyWithSuppliedProperty(j, key, j.objectExpression([])); Object.keys(subProps[key]).forEach( (optionProperty) => { if(Array.isArray(subProps[key][optionProperty])) { - const optionArray = transformUtils.createArrayWithChildren( + const optionArray = utils.createArrayWithChildren( j, optionProperty, subProps[key][optionProperty], true ); optionVal.value.properties.push(optionArray); } else { - optionVal.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, - optionProperty, - transformUtils.createIdentifierOrLiteral( - j, subProps[key][optionProperty] - ) - ) - ); + utils.pushCreateProperty(j, optionVal, optionProperty, subProps[key][optionProperty]); } }); } @@ -48,22 +38,22 @@ function createOption(j, subProps, key) { } // Module.rules.rule.use function createUseProperties(j, key, subProps) { - let useVal = transformUtils.createEmptyArrayProperty(j, key); + let useVal = utils.createEmptyArrayProperty(j, key); Object.keys(subProps[key]).forEach( (optionProperty) => { if(typeof(subProps[key][optionProperty]) === 'string') { useVal.value.elements.push( - transformUtils.createIdentifierOrLiteral(subProps[key][optionProperty]) + utils.createIdentifierOrLiteral(subProps[key][optionProperty]) ); } else { let loaderProperty = j.objectExpression([]); Object.keys(subProps[key][optionProperty]).forEach( subOptionProp => { if(typeof(subProps[key][optionProperty][subOptionProp]) === 'string') { loaderProperty.properties.push( - transformUtils.createPropertyWithSuppliedProperty( + utils.createPropertyWithSuppliedProperty( j, subOptionProp, - transformUtils.createIdentifierOrLiteral( + utils.createIdentifierOrLiteral( j, subProps[key][optionProperty][subOptionProp] ) ) @@ -72,17 +62,17 @@ function createUseProperties(j, key, subProps) { let subSubProps = j.objectExpression([]); Object.keys(subProps[key][optionProperty][subOptionProp]).forEach( (underlyingOption) => { subSubProps.properties.push( - transformUtils.createPropertyWithSuppliedProperty( + utils.createPropertyWithSuppliedProperty( j, underlyingOption, - transformUtils.createIdentifierOrLiteral( + utils.createIdentifierOrLiteral( j, subProps[key][optionProperty][subOptionProp][underlyingOption] ) ) ); }); loaderProperty.properties.push( - transformUtils.createPropertyWithSuppliedProperty(j, subOptionProp, subSubProps) + utils.createPropertyWithSuppliedProperty(j, subOptionProp, subSubProps) ); } }); diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index 09b6968e48f..d24db31dd56 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -367,6 +367,30 @@ function createExternalRegExp(j, prop) { return j.literal(regExpProp.value); } +/* +* @function pushCreateProperty +* +* Creates a property and pushes the value to a node +* @param j — jscodeshift API +* @param { Node } p - Node to push against +* @param { String } key - key used as identifier +* @param { String } val - property value +* @returns - { Node } - Returns node the pushed property +*/ + +function pushCreateProperty(j, p, key, val) { + let property; + if(val.hasOwnProperty('type')) { + property = val; + } else { + property = createIdentifierOrLiteral(j, val); + } + + return p.value.properties.push( + createPropertyWithSuppliedProperty(j, key, property) + ); +} + module.exports = { safeTraverse, createProperty, @@ -383,5 +407,6 @@ module.exports = { createArrayWithChildren, createEmptyArrayProperty, createPropertyWithSuppliedProperty, - createExternalRegExp + createExternalRegExp, + pushCreateProperty }; From 28fc6f08636dd5d4541bb6f611dc65934a771bb6 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 22 Apr 2017 23:49:31 +0200 Subject: [PATCH 064/101] enhancements: use createpushval for all transforms --- lib/creator/transformations/node/node.js | 20 +++------ ...others.test.js.snap => other.test.js.snap} | 10 ++--- .../{others-0.input.js => other-0.input.js} | 0 lib/creator/transformations/other/amd.js | 21 +++------- lib/creator/transformations/other/bail.js | 8 +--- lib/creator/transformations/other/cache.js | 8 +--- .../transformations/other/other.test.js | 10 +++++ .../transformations/other/others.test.js | 10 ----- lib/creator/transformations/other/profile.js | 8 +--- lib/creator/transformations/output/output.js | 31 ++++---------- .../performance/performance.js | 22 +++------- .../transformations/plugins/plugins.js | 4 +- .../transformations/resolve/resolve.js | 41 ++++++------------- lib/creator/transformations/stats/stats.js | 23 +++++------ lib/creator/transformations/target/target.js | 5 +-- lib/creator/transformations/watch/watch.js | 5 +-- .../transformations/watch/watchOptions.js | 30 ++++---------- 17 files changed, 82 insertions(+), 174 deletions(-) rename lib/creator/transformations/other/__snapshots__/{others.test.js.snap => other.test.js.snap} (66%) rename lib/creator/transformations/other/__testfixtures__/{others-0.input.js => other-0.input.js} (100%) create mode 100644 lib/creator/transformations/other/other.test.js delete mode 100644 lib/creator/transformations/other/others.test.js diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index f596c4140f0..5af7710e066 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -16,23 +16,15 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createNodeProperty(p) { + utils.pushCreateProperty(j, p, 'node', j.objectExpression([])); + let node = p.value.properties; - node.push( - transformUtils.createPropertyWithSuppliedProperty(j, 'node', j.objectExpression([])) - ); node.filter(n => - (transformUtils.safeTraverse(n, ['key', 'name']) === 'node') + (utils.safeTraverse(n, ['key', 'name']) === 'node') ).forEach( (prop) => { Object.keys(webpackProperties.node).forEach( (webpackProp) => { - prop.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, - webpackProp, - transformUtils.createIdentifierOrLiteral( - j, - webpackProperties.node[webpackProp] - ) - ) + utils.pushCreateProperty( + j, prop, webpackProp, webpackProperties.node[webpackProp] ); }); }); diff --git a/lib/creator/transformations/other/__snapshots__/others.test.js.snap b/lib/creator/transformations/other/__snapshots__/other.test.js.snap similarity index 66% rename from lib/creator/transformations/other/__snapshots__/others.test.js.snap rename to lib/creator/transformations/other/__snapshots__/other.test.js.snap index da78db4d508..8b1a26010b9 100644 --- a/lib/creator/transformations/other/__snapshots__/others.test.js.snap +++ b/lib/creator/transformations/other/__snapshots__/other.test.js.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`amd transforms correctly using "others-0" data 1`] = ` +exports[`amd transforms correctly using "other-0" data 1`] = ` "module.exports = { entry: 'index.js', output: { @@ -15,7 +15,7 @@ exports[`amd transforms correctly using "others-0" data 1`] = ` " `; -exports[`bail transforms correctly using "others-0" data 1`] = ` +exports[`bail transforms correctly using "other-0" data 1`] = ` "module.exports = { entry: 'index.js', output: { @@ -27,7 +27,7 @@ exports[`bail transforms correctly using "others-0" data 1`] = ` " `; -exports[`cache transforms correctly using "others-0" data 1`] = ` +exports[`cache transforms correctly using "other-0" data 1`] = ` "module.exports = { entry: 'index.js', output: { @@ -39,7 +39,7 @@ exports[`cache transforms correctly using "others-0" data 1`] = ` " `; -exports[`cache transforms correctly using "others-0" data 2`] = ` +exports[`cache transforms correctly using "other-0" data 2`] = ` "module.exports = { entry: 'index.js', output: { @@ -51,7 +51,7 @@ exports[`cache transforms correctly using "others-0" data 2`] = ` " `; -exports[`profile transforms correctly using "others-0" data 1`] = ` +exports[`profile transforms correctly using "other-0" data 1`] = ` "module.exports = { entry: 'index.js', output: { diff --git a/lib/creator/transformations/other/__testfixtures__/others-0.input.js b/lib/creator/transformations/other/__testfixtures__/other-0.input.js similarity index 100% rename from lib/creator/transformations/other/__testfixtures__/others-0.input.js rename to lib/creator/transformations/other/__testfixtures__/other-0.input.js diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index 1b5bfd116b5..c39b7136ff0 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -16,25 +16,14 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createAMDProperty(p) { + utils.pushCreateProperty(j, p, 'amd', j.objectExpression([])); let amdNode = p.value.properties; - amdNode.push( - transformUtils.createPropertyWithSuppliedProperty( - j, 'amd', j.objectExpression([]) - ) - ); amdNode.filter(n => - (transformUtils.safeTraverse(n, ['key', 'name']) === 'amd') + (utils.safeTraverse(n, ['key', 'name']) === 'amd') ).forEach( (prop) => { Object.keys(webpackProperties['amd']).forEach( (webpackProp) => { - prop.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, - webpackProp, - transformUtils.createIdentifierOrLiteral( - j, - webpackProperties.amd[webpackProp] - ) - ) + utils.pushCreateProperty( + j, prop, webpackProp, webpackProperties.amd[webpackProp] ); }); }); diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index e1cee49eca6..316cb95ae39 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -17,11 +17,7 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createBailProperty(p) { - let bailVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['bail']); - - return p.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty(j, 'bail', bailVal) - ); + return utils.pushCreateProperty(j, p, 'bail', webpackProperties['bail']); } if(webpackProperties['bail']) { diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index f049f49843c..821e18240d4 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -16,11 +16,7 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createCacheProperty(p) { - let cacheVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['cache']); - - return p.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty(j, 'cache', cacheVal) - ); + return utils.pushCreateProperty(j, p, 'cache', webpackProperties['cache']); } if(webpackProperties['cache']) { diff --git a/lib/creator/transformations/other/other.test.js b/lib/creator/transformations/other/other.test.js new file mode 100644 index 00000000000..de593101e1b --- /dev/null +++ b/lib/creator/transformations/other/other.test.js @@ -0,0 +1,10 @@ +const defineTest = require('../../../transformations/defineTest'); + +defineTest(__dirname, 'amd', 'other-0', {amd : { + jQuery: true, + kQuery: false} +}); +defineTest(__dirname, 'bail', 'other-0', {bail : true}); +defineTest(__dirname, 'cache', 'other-0', {cache : true}); +defineTest(__dirname, 'cache', 'other-0', {cache : 'cacheVal'}); +defineTest(__dirname, 'profile', 'other-0', {profile : true}); diff --git a/lib/creator/transformations/other/others.test.js b/lib/creator/transformations/other/others.test.js deleted file mode 100644 index 477c89cc2de..00000000000 --- a/lib/creator/transformations/other/others.test.js +++ /dev/null @@ -1,10 +0,0 @@ -const defineTest = require('../../../transformations/defineTest'); - -defineTest(__dirname, 'amd', 'others-0', {amd : { - jQuery: true, - kQuery: false} -}); -defineTest(__dirname, 'bail', 'others-0', {bail : true}); -defineTest(__dirname, 'cache', 'others-0', {cache : true}); -defineTest(__dirname, 'cache', 'others-0', {cache : 'cacheVal'}); -defineTest(__dirname, 'profile', 'others-0', {profile : true}); diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index a9f661f0768..58807740687 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -16,11 +16,7 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createProfileProperty(p) { - let profileVal = transformUtils.createIdentifierOrLiteral(j, webpackProperties['profile']); - - return p.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty(j, 'profile', profileVal) - ); + return utils.pushCreateProperty(j, p, 'profile', webpackProperties['profile']); } if(webpackProperties['profile']) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 43b95aab4ed..8582f7de91a 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -1,6 +1,6 @@ const webpackOutputTypes = require('./output-types'); const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -17,37 +17,20 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createOutputProperties(p) { + utils.pushCreateProperty(j, p, 'output', j.objectExpression([])); let outputNode = p.value.properties; - outputNode.push( - transformUtils.createPropertyWithSuppliedProperty( - j, - 'output', - j.objectExpression([]) - ) - ); - outputNode.filter( n => - (transformUtils.safeTraverse(n, ['key', 'name']) === 'output') + (utils.safeTraverse(n, ['key', 'name']) === 'output') ).forEach( (prop) => { Object.keys(webpackProperties.output).forEach( (webpackProp) => { if(webpackOutputTypes.includes(webpackProp)) { if(webpackProperties.output[webpackProp].__paths) { - let regExpProp = transformUtils.createExternalRegExp(j, webpackProperties.output[webpackProp]); - - prop.value.properties.push( - j.property('init', j.identifier(webpackProp), regExpProp) - ); + let regExpProp = utils.createExternalRegExp(j, webpackProperties.output[webpackProp]); + utils.pushCreateProperty(j, prop, webpackProp, regExpProp); } else { - prop.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, - webpackProp, - transformUtils.createIdentifierOrLiteral( - j, - webpackProperties.output[webpackProp] - ) - ) + utils.pushCreateProperty( + j, prop, webpackProp, webpackProperties.output[webpackProp] ); } } diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index ca15babcf8b..150d62472cb 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -1,6 +1,6 @@ const performanceTypes = require('./performance-types'); const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -18,26 +18,16 @@ module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createPerformanceProperty(p) { + + utils.pushCreateProperty(j, p, 'performance', j.objectExpression([])); let performanceNode = p.value.properties; - performanceNode.push( - transformUtils.createPropertyWithSuppliedProperty( - j, 'performance', j.objectExpression([]) - ) - ); performanceNode.filter(n => - (transformUtils.safeTraverse(n, ['key', 'name']) === 'performance') + (utils.safeTraverse(n, ['key', 'name']) === 'performance') ).forEach( (prop) => { Object.keys(webpackProperties.performance).forEach( (webpackProp) => { if(performanceTypes.includes(webpackProp)) { - prop.value.properties.push( - transformUtils.createPropertyWithSuppliedProperty( - j, - webpackProp, - transformUtils.createIdentifierOrLiteral( - j, - webpackProperties.performance[webpackProp] - ) - ) + utils.pushCreateProperty( + j, prop, webpackProp, webpackProperties.performance[webpackProp] ); } }); diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index 33498838924..d2b39d32d2e 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* * @@ -15,7 +15,7 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createPluginsProperty(p) { - const pluginArray = transformUtils.createArrayWithChildren(j, 'plugins', webpackProperties); + const pluginArray = utils.createArrayWithChildren(j, 'plugins', webpackProperties); return p.value.properties.push(pluginArray); } if(webpackProperties['plugins'] && Array.isArray(webpackProperties['plugins'])) { diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index a8d5d41f893..ba36d9a4129 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -1,5 +1,6 @@ const resolveTypes = require('./resolve-types'); const isAssignment = require('../../utils/is-assignment'); +const utils = require('../../../transformations/utils'); /* * @@ -15,34 +16,25 @@ const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createResolveProperties(p) { + utils.pushCreateProperty(j, p, 'resolve', j.objectExpression([])); let resolveNode = p.value.properties; - resolveNode.push(j.property('init', j.identifier('resolve'), j.objectExpression([]))); resolveNode.filter(n => n.key.name === 'resolve').forEach( (prop) => { Object.keys(webpackProperties.resolve).forEach( (webpackProp) => { if(resolveTypes.includes(webpackProp) || webpackProp === 'resolveLoader') { if(Array.isArray(webpackProperties.resolve[webpackProp])) { // if we got a type, we make it an array - const resolveArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); - webpackProperties.resolve[webpackProp].forEach( (n) => { - return resolveArray.value.elements.push(j.identifier(n)); - }); + const resolveArray = utils.createArrayWithChildren( + j, webpackProp, webpackProperties.resolve[webpackProp], true + ); prop.value.properties.push(resolveArray); } else if(typeof(webpackProperties.resolve[webpackProp]) === 'boolean') { - let boolExp = j.property( - 'init', - j.identifier(webpackProp), - j.literal(webpackProperties.resolve[webpackProp]) + utils.pushCreateProperty( + j, prop, webpackProp, webpackProperties.resolve[webpackProp] ); - prop.value.properties.push(boolExp); } else { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - j.objectExpression([])) - ); + utils.pushCreateProperty(j, prop, webpackProp, j.objectExpression([])); prop.value.properties.forEach( (resolveProp) => { if(resolveProp.key.name === webpackProp) { if(resolveProp.key.name === 'cachePredicate') { @@ -54,14 +46,9 @@ module.exports = function(j, ast, yeomanConfig) { } Object.keys(webpackProperties.resolve[webpackProp]).forEach( (aliasProps) => { if(Array.isArray(webpackProperties.resolve[webpackProp][aliasProps])) { - const resolveLoaderArray = j.property( - 'init', - j.identifier(aliasProps), - j.arrayExpression([]) + const resolveLoaderArray = utils.createArrayWithChildren( + j, aliasProps, webpackProperties.resolve[webpackProp][aliasProps], true ); - webpackProperties.resolve[webpackProp][aliasProps].forEach( (n) => { - return resolveLoaderArray.value.elements.push(j.identifier(n)); - }); resolveProp.value.properties.push(resolveLoaderArray); } else if(webpackProperties.resolve[webpackProp][aliasProps].length > 1) { @@ -70,12 +57,8 @@ module.exports = function(j, ast, yeomanConfig) { webpackProperties.resolve[webpackProp][aliasProps] )); } else { - resolveProp.value.properties.push( - j.property( - 'init', - j.identifier(aliasProps), - j.identifier(webpackProperties.resolve[webpackProp][aliasProps]) - ) + utils.pushCreateProperty( + j, resolveProp, aliasProps, webpackProperties.resolve[webpackProp][aliasProps] ); } } diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index a74013afac1..c93cdc9e3fc 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -1,6 +1,6 @@ const statsTypes = require('./stats-types'); const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* * @@ -16,25 +16,22 @@ const transformUtils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createStatsProperty(p) { + utils.pushCreateProperty(j, p, 'stats', j.objectExpression([])); let statsNode = p.value.properties; - statsNode.push(j.property('init', j.identifier('stats'), j.objectExpression([]))); - statsNode.filter(n => n.key.name === 'stats').forEach( (prop) => { + statsNode.filter(n => + (utils.safeTraverse(n, ['key', 'name']) === 'stats') + ).forEach( (prop) => { Object.keys(webpackProperties.stats).forEach( (webpackProp) => { if(statsTypes.includes(webpackProp)) { if(Array.isArray(webpackProperties.stats[webpackProp])) { - const statsArray = j.property('init', j.identifier(webpackProp), j.arrayExpression([])); - webpackProperties.stats[webpackProp].forEach( (n) => { - return statsArray.value.elements.push(j.identifier(n)); - }); + const statsArray = utils.createArrayWithChildren( + j, webpackProp, webpackProperties.stats[webpackProp], true + ); prop.value.properties.push(statsArray); } else { - prop.value.properties.push( - j.property( - 'init', - j.identifier(webpackProp), - transformUtils.createIdentifierOrLiteral(j, webpackProperties.stats[webpackProp]) - ) + utils.pushCreateProperty( + j, prop, webpackProp, webpackProperties.stats[webpackProp] ); } } else { diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 35bd81b320e..b1a17ad8c15 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,4 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); +const utils = require('../../../transformations/utils'); /* * @@ -14,9 +15,7 @@ const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createTargetProperty(p) { - return p.value.properties.push( - j.property('init', j.identifier('target'), j.identifier(webpackProperties['target'])) - ); + return utils.pushCreateProperty(j, p, 'target', webpackProperties['target']); } if(webpackProperties['target'] && webpackProperties['target'].length) { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createTargetProperty)); diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 79cafe6d69c..7bf7a927102 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,4 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); +const utils = require('../../../transformations/utils'); /* * @@ -14,9 +15,7 @@ const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchProperty(p) { - return p.value.properties.push( - j.property('init', j.identifier('watch'), j.literal(webpackProperties['watch'])) - ); + return utils.pushCreateProperty(j, p, 'watch', webpackProperties['watch']); } if(typeof(webpackProperties['watch']) === 'boolean') { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchProperty)); diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index 6c95b365523..3e32052dd34 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -1,5 +1,6 @@ const watchOptionTypes = require('./watchOptions-types'); const isAssignment = require('../../utils/is-assignment'); +const utils = require('../../../transformations/utils'); /* * @@ -15,35 +16,22 @@ const isAssignment = require('../../utils/is-assignment'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; function createWatchOptionsProperty(p) { - let watchOptionsNode = p.value.properties; - watchOptionsNode.push(j.property('init', j.identifier('watchOptions'), j.objectExpression([]))); - watchOptionsNode.filter(n => n.key.name === 'watchOptions').forEach( (prop) => { + utils.pushCreateProperty(j, p, 'watchOptions', j.objectExpression([])); + p.value.properties.filter(n => + (utils.safeTraverse(n, ['key', 'name']) === 'watchOptions') + ).forEach( (prop) => { Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { if(watchOptionTypes.includes(watchOption)) { - if(typeof(webpackProperties['watchOptions'][watchOption]) === 'number') { - prop.value.properties.push( - j.property( - 'init', - j.identifier(watchOption), - j.literal(webpackProperties['watchOptions'][watchOption]) - ) - ); - } else { - prop.value.properties.push( - j.property( - 'init', - j.identifier(watchOption), - j.identifier(webpackProperties['watchOptions'][watchOption]) - ) - ); - } + utils.pushCreateProperty( + j, prop, watchOption, webpackProperties.watchOptions[watchOption] + ); } else { throw new Error('Unknown Property', watchOption); } }); }); } - if(webpackProperties['watchOptions'] && webpackProperties['watchOptions']) { + if(webpackProperties['watchOptions']) { return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchOptionsProperty)); } else { return ast; From 115a73a74643be54ea8f9697e4df285b27ae827d Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 23 Apr 2017 14:59:42 +0200 Subject: [PATCH 065/101] enhancements: use new utility to create single properties --- .../transformations/context/context.js | 8 ++------ .../transformations/devtool/devtool.js | 7 ++----- lib/creator/transformations/entry/entry.js | 14 +++++++------- lib/creator/transformations/module/module.js | 2 +- lib/creator/transformations/node/node.js | 2 +- lib/creator/transformations/other/amd.js | 2 +- lib/creator/transformations/other/bail.js | 8 ++------ lib/creator/transformations/other/cache.js | 7 ++----- lib/creator/transformations/other/profile.js | 7 ++----- lib/creator/transformations/output/output.js | 2 +- .../performance/performance.js | 2 +- .../transformations/plugins/plugins.js | 2 +- .../transformations/resolve/resolve.js | 2 +- lib/creator/transformations/stats/stats.js | 2 +- lib/creator/transformations/target/target.js | 8 +++----- lib/creator/transformations/watch/watch.js | 7 ++----- .../transformations/watch/watchOptions.js | 2 +- lib/creator/utils/is-assignment.js | 9 +++++++-- lib/transformations/utils.js | 19 ++++++++++++++++++- 19 files changed, 56 insertions(+), 56 deletions(-) diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 2f8179f3830..2f6d96d1075 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const utils = require('../../../transformations/utils'); +const createSingularProperty = require('../../../transformations/utils').createSingularProperty; /* @@ -16,13 +16,9 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; - function createContextProperty(p) { - return utils.pushCreateProperty(j, p, 'context', webpackProperties['context']); - } - if(webpackProperties['context']) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createContextProperty)); + .filter(p => isAssignment(j, p, createSingularProperty, 'context', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index 23067e42422..006c7037984 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const utils = require('../../../transformations/utils'); +const createSingularProperty = require('../../../transformations/utils').createSingularProperty; /* @@ -16,12 +16,9 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; - function createDevToolProperty(p) { - return utils.pushCreateProperty(j, p, 'devtool', webpackProperties['devtool']); - } if(webpackProperties['devtool']) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createDevToolProperty)); + .filter(p => isAssignment(j, p, createSingularProperty, 'devtool', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index a9da5ac6e3d..36ad2e304d8 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const transformUtils = require('../../../transformations/utils'); +const utils = require('../../../transformations/utils'); /* @@ -20,17 +20,17 @@ module.exports = function(j, ast, yeomanConfig) { function addEntryPoints(entries) { if(Array.isArray(entries)) { - return j.arrayExpression(entries.map(entry => transformUtils.createIdentifierOrLiteral(j, entry))); + return j.arrayExpression(entries.map(entry => utils.createIdentifierOrLiteral(j, entry))); } else if (typeof entries === 'string') { - return transformUtils.createIdentifierOrLiteral(j, entries); + return utils.createIdentifierOrLiteral(j, entries); } const entryKeys = Object.keys(entries); if (entryKeys && entryKeys.length) { return j.objectExpression( entryKeys.map(entryKey => { return j.property( 'init', - transformUtils.createIdentifierOrLiteral(j, entryKey), - transformUtils.createIdentifierOrLiteral(j, entries[entryKey]) + utils.createIdentifierOrLiteral(j, entryKey), + utils.createIdentifierOrLiteral(j, entries[entryKey]) ); }) ); @@ -41,12 +41,12 @@ module.exports = function(j, ast, yeomanConfig) { let entryNode = p.value.properties; entryNode.push( j.property( 'init', - transformUtils.createIdentifierOrLiteral(j, 'entry'), + utils.createIdentifierOrLiteral(j, 'entry'), addEntryPoints(webpackProperties['entry']))); } if(webpackProperties['entry']) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createEntryProperty)); + .filter(p => isAssignment(null, p, createEntryProperty)); } else { return ast; } diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 1c800e0fdca..db165e33047 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -111,6 +111,6 @@ module.exports = function(j, ast, yeomanConfig) { return ast; } else { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createModuleProperties)); + .filter(p => isAssignment(null, p, createModuleProperties)); } }; diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index 5af7710e066..36626bc67f3 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -31,7 +31,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['node']) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createNodeProperty)); + .filter(p => isAssignment(null, p, createNodeProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index c39b7136ff0..3d328f97767 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -30,7 +30,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['amd'] && typeof(webpackProperties['amd']) === 'object') { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createAMDProperty)); + .filter(p => isAssignment(null, p, createAMDProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index 316cb95ae39..c4441442502 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const utils = require('../../../transformations/utils'); +const createSingularProperty = require('../../../transformations/utils').createSingularProperty; /* @@ -16,13 +16,9 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; - function createBailProperty(p) { - return utils.pushCreateProperty(j, p, 'bail', webpackProperties['bail']); - } - if(webpackProperties['bail']) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createBailProperty)); + .filter(p => isAssignment(j, p, createSingularProperty, 'bail', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index 821e18240d4..84f3df655f8 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const utils = require('../../../transformations/utils'); +const createSingularProperty = require('../../../transformations/utils').createSingularProperty; /* @@ -15,13 +15,10 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; - function createCacheProperty(p) { - return utils.pushCreateProperty(j, p, 'cache', webpackProperties['cache']); - } if(webpackProperties['cache']) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createCacheProperty)); + .filter(p => isAssignment(j, p, createSingularProperty, 'cache', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index 58807740687..411034057ec 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const utils = require('../../../transformations/utils'); +const createSingularProperty = require('../../../transformations/utils').createSingularProperty; /* @@ -15,12 +15,9 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; - function createProfileProperty(p) { - return utils.pushCreateProperty(j, p, 'profile', webpackProperties['profile']); - } if(webpackProperties['profile']) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createProfileProperty)); + .filter(p => isAssignment(j, p, createSingularProperty, 'profile', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 8582f7de91a..0140cad6009 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -38,7 +38,7 @@ module.exports = function(j, ast, yeomanConfig) { }); } if(webpackProperties['output']) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createOutputProperties)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createOutputProperties)); } else { return ast; } diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 150d62472cb..e7f414dcc94 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -35,7 +35,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(webpackProperties['performance'] && typeof(webpackProperties['performance']) === 'object') { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(p, createPerformanceProperty)); + .filter(p => isAssignment(null, p, createPerformanceProperty)); } else { return ast; } diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index d2b39d32d2e..e74301cf1b2 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -19,7 +19,7 @@ module.exports = function(j, ast, yeomanConfig) { return p.value.properties.push(pluginArray); } if(webpackProperties['plugins'] && Array.isArray(webpackProperties['plugins'])) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createPluginsProperty)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createPluginsProperty)); } else { return ast; } diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index ba36d9a4129..261ba6ba15a 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -71,7 +71,7 @@ module.exports = function(j, ast, yeomanConfig) { }); } if(webpackProperties['resolve'] ) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createResolveProperties)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createResolveProperties)); } else { return ast; diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index c93cdc9e3fc..0c2292cd849 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -41,7 +41,7 @@ module.exports = function(j, ast, yeomanConfig) { }); } if(webpackProperties['stats'] && typeof(webpackProperties['stats']) === 'object') { - return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createStatsProperty)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createStatsProperty)); } // FIXME -> HOC AssignmentExpression else if(webpackProperties['stats'] && webpackProperties['stats'].length) { diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index b1a17ad8c15..a048220929f 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const utils = require('../../../transformations/utils'); +const createSingularProperty = require('../../../transformations/utils').createSingularProperty; /* * @@ -14,11 +14,9 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; - function createTargetProperty(p) { - return utils.pushCreateProperty(j, p, 'target', webpackProperties['target']); - } + if(webpackProperties['target'] && webpackProperties['target'].length) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createTargetProperty)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(j, p, createSingularProperty, 'target', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 7bf7a927102..16b0ac5be96 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,5 +1,5 @@ const isAssignment = require('../../utils/is-assignment'); -const utils = require('../../../transformations/utils'); +const createSingularProperty = require('../../../transformations/utils').createSingularProperty; /* * @@ -14,11 +14,8 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, yeomanConfig) { const webpackProperties = yeomanConfig.webpackOptions; - function createWatchProperty(p) { - return utils.pushCreateProperty(j, p, 'watch', webpackProperties['watch']); - } if(typeof(webpackProperties['watch']) === 'boolean') { - return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchProperty)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(j, p, createSingularProperty, 'watch', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index 3e32052dd34..d6a22a250d6 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -32,7 +32,7 @@ module.exports = function(j, ast, yeomanConfig) { }); } if(webpackProperties['watchOptions']) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(p, createWatchOptionsProperty)); + return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createWatchOptionsProperty)); } else { return ast; } diff --git a/lib/creator/utils/is-assignment.js b/lib/creator/utils/is-assignment.js index 08f6160b003..040ea41822c 100644 --- a/lib/creator/utils/is-assignment.js +++ b/lib/creator/utils/is-assignment.js @@ -1,5 +1,10 @@ -module.exports = function(p, cb) { +module.exports = function(j, p, cb, identifier, property) { if(p.parent.value.type === 'AssignmentExpression') { - return cb(p); + if(j) { + return cb(j, p, identifier, property); + } + else { + return cb(p); + } } }; diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index d24db31dd56..d048272c948 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -391,6 +391,22 @@ function pushCreateProperty(j, p, key, val) { ); } +/* +* @function createSingularProperty +* +* Creates an assignment with given properties from yeoman +* @param j — jscodeshift API +* @param { Node } p - Node to push against +* @param { String } name - key used as identifier +* @param { String } webpackProperties - property value to add with key +* @returns - { Node } - Returns node the pushed property +*/ + +function createSingularProperty(j, p, name, webpackProperties) { + return pushCreateProperty(j, p, name, webpackProperties[name]); +} + + module.exports = { safeTraverse, createProperty, @@ -408,5 +424,6 @@ module.exports = { createEmptyArrayProperty, createPropertyWithSuppliedProperty, createExternalRegExp, - pushCreateProperty + pushCreateProperty, + createSingularProperty }; From f3ad8af11e0e64eec88542020bca7d102bbecc3b Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 23 Apr 2017 16:19:48 +0200 Subject: [PATCH 066/101] enhancements: add test for utility functions --- .../transformations/context/context.js | 2 +- .../transformations/devtool/devtool.js | 2 +- lib/creator/transformations/entry/entry.js | 2 +- .../transformations/externals/externals.js | 2 +- lib/creator/transformations/module/module.js | 4 +- lib/creator/transformations/module/utils.js | 12 +-- lib/creator/transformations/node/node.js | 2 +- lib/creator/transformations/other/amd.js | 2 +- lib/creator/transformations/other/bail.js | 2 +- lib/creator/transformations/other/cache.js | 2 +- lib/creator/transformations/other/merge.js | 2 +- lib/creator/transformations/other/profile.js | 2 +- lib/creator/transformations/output/output.js | 2 +- .../performance/performance.js | 2 +- .../transformations/plugins/plugins.js | 2 +- .../transformations/resolve/resolve.js | 2 +- lib/creator/transformations/stats/stats.js | 2 +- lib/creator/transformations/target/target.js | 2 +- lib/creator/transformations/watch/watch.js | 2 +- .../transformations/watch/watchOptions.js | 2 +- .../__snapshots__/utils.test.js.snap | 36 +++++++ lib/transformations/utils.js | 38 +++++-- lib/transformations/utils.test.js | 101 ++++++++++++++++++ 23 files changed, 195 insertions(+), 32 deletions(-) diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 2f6d96d1075..7bf7aadea41 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const createSingularProperty = require('../../../transformations/utils').createSingularProperty; diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index 006c7037984..ca555d9fae6 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const createSingularProperty = require('../../../transformations/utils').createSingularProperty; diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index 36ad2e304d8..ef9a194d3bb 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 7e2a026e2d4..f4cf7aa473e 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -26,7 +26,7 @@ module.exports = function(j, ast, yeomanConfig) { if(typeof(n) !== 'string') { for(let key in n) { objectOfArray.properties.push( - utils.createPropertyWithSuppliedProperty( + utils.createObjectWithSuppliedProperty( j, key, utils.createIdentifierOrLiteral(j, n[key])) ); } diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index db165e33047..04164f7db0b 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -1,5 +1,5 @@ const webpackModuleTypes = require('./module-types'); -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const localUtils = require('./utils'); const utils = require('../../../transformations/utils'); @@ -63,7 +63,7 @@ module.exports = function(j, ast, yeomanConfig) { } if(key === 'enforce' || key === 'loader') { moduleProp.value.elements[seen].properties.push( - utils.createPropertyWithSuppliedProperty( + utils.createObjectWithSuppliedProperty( j, key, utils.createIdentifierOrLiteral( diff --git a/lib/creator/transformations/module/utils.js b/lib/creator/transformations/module/utils.js index 58865e8b171..b0865ea824d 100644 --- a/lib/creator/transformations/module/utils.js +++ b/lib/creator/transformations/module/utils.js @@ -9,7 +9,7 @@ function regExpStrategy(j, webpackProperties, webpackProp, prop) { // Module.rules.myRule.test function createTestProperty(j, moduleProp, seen, key, subProps) { moduleProp.value.elements[seen].properties.push( - utils.createPropertyWithSuppliedProperty(j, key, j.literal(subProps[key])) + utils.createObjectWithSuppliedProperty(j, key, j.literal(subProps[key])) ); } // Module.rules.myRule.option @@ -19,9 +19,9 @@ function createOption(j, subProps, key) { if(typeof(subProps[key]) === 'string') { optionProp = utils.createIdentifierOrLiteral(j, subProps[key]); - optionVal = utils.createPropertyWithSuppliedProperty(j, key, optionProp); + optionVal = utils.createObjectWithSuppliedProperty(j, key, optionProp); } else { - optionVal = utils.createPropertyWithSuppliedProperty(j, key, j.objectExpression([])); + optionVal = utils.createObjectWithSuppliedProperty(j, key, j.objectExpression([])); Object.keys(subProps[key]).forEach( (optionProperty) => { if(Array.isArray(subProps[key][optionProperty])) { @@ -50,7 +50,7 @@ function createUseProperties(j, key, subProps) { Object.keys(subProps[key][optionProperty]).forEach( subOptionProp => { if(typeof(subProps[key][optionProperty][subOptionProp]) === 'string') { loaderProperty.properties.push( - utils.createPropertyWithSuppliedProperty( + utils.createObjectWithSuppliedProperty( j, subOptionProp, utils.createIdentifierOrLiteral( @@ -62,7 +62,7 @@ function createUseProperties(j, key, subProps) { let subSubProps = j.objectExpression([]); Object.keys(subProps[key][optionProperty][subOptionProp]).forEach( (underlyingOption) => { subSubProps.properties.push( - utils.createPropertyWithSuppliedProperty( + utils.createObjectWithSuppliedProperty( j, underlyingOption, utils.createIdentifierOrLiteral( @@ -72,7 +72,7 @@ function createUseProperties(j, key, subProps) { ); }); loaderProperty.properties.push( - utils.createPropertyWithSuppliedProperty(j, subOptionProp, subSubProps) + utils.createObjectWithSuppliedProperty(j, subOptionProp, subSubProps) ); } }); diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index 36626bc67f3..66aee1c0ac5 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index 3d328f97767..b9e86ad922c 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index c4441442502..2cbc03df7b7 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const createSingularProperty = require('../../../transformations/utils').createSingularProperty; diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index 84f3df655f8..5c4fe10a534 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const createSingularProperty = require('../../../transformations/utils').createSingularProperty; diff --git a/lib/creator/transformations/other/merge.js b/lib/creator/transformations/other/merge.js index fc03000158d..e17bc74c75b 100644 --- a/lib/creator/transformations/other/merge.js +++ b/lib/creator/transformations/other/merge.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; /* diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index 411034057ec..dfa87b867d8 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const createSingularProperty = require('../../../transformations/utils').createSingularProperty; diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 0140cad6009..e0b418ac1b0 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -1,5 +1,5 @@ const webpackOutputTypes = require('./output-types'); -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index e7f414dcc94..80dbb98fd69 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -1,5 +1,5 @@ const performanceTypes = require('./performance-types'); -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index e74301cf1b2..4e129205461 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); /* diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index 261ba6ba15a..1baeaaf6204 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -1,5 +1,5 @@ const resolveTypes = require('./resolve-types'); -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); /* diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index 0c2292cd849..6ac506fc5fa 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -1,5 +1,5 @@ const statsTypes = require('./stats-types'); -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); /* diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index a048220929f..845678c159d 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const createSingularProperty = require('../../../transformations/utils').createSingularProperty; /* diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 16b0ac5be96..dca2d49d1b6 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,4 +1,4 @@ -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const createSingularProperty = require('../../../transformations/utils').createSingularProperty; /* diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index d6a22a250d6..c327aea41f7 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -1,5 +1,5 @@ const watchOptionTypes = require('./watchOptions-types'); -const isAssignment = require('../../utils/is-assignment'); +const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); /* diff --git a/lib/transformations/__snapshots__/utils.test.js.snap b/lib/transformations/__snapshots__/utils.test.js.snap index 400542763b9..38442c773dd 100644 --- a/lib/transformations/__snapshots__/utils.test.js.snap +++ b/lib/transformations/__snapshots__/utils.test.js.snap @@ -17,6 +17,14 @@ exports[`utils checkIfExistsAndAddValue should override prop if it exists 1`] = " `; +exports[`utils createArrayWithChildren should add all children of an array to a new one with a supplied key 1`] = `"myVeryOwnKey: ['hello', world]"`; + +exports[`utils createArrayWithChildren should find an prop that matches key and create an array with it 1`] = `"react: ['bo']"`; + +exports[`utils createEmptyArrayProperty should create an array with no properties 1`] = `"its-lit: []"`; + +exports[`utils createExternalRegExp should create an regExp property that has been parsed by jscodeshift 1`] = `"\\"\\\\t\\""`; + exports[`utils createIdentifierOrLiteral should create basic literal 1`] = `"'stringLiteral'"`; exports[`utils createIdentifierOrLiteral should create boolean 1`] = `"true"`; @@ -25,6 +33,8 @@ exports[`utils createLiteral should create basic literal 1`] = `"\\"stringLitera exports[`utils createLiteral should create boolean 1`] = `"true"`; +exports[`utils createObjectWithSuppliedProperty should create an object with a property supplied by us 1`] = `"its-lit: {}"`; + exports[`utils createOrUpdatePluginByName should add an object as an argument 1`] = ` "[new Plugin({ \\"foo\\": true @@ -77,4 +87,30 @@ exports[`utils createProperty should create properties for non-literal keys 1`] }" `; +exports[`utils createSingularProperty should create an single property with no nested properties 1`] = ` +"module.exports = { + context: Heyho +}" +`; + exports[`utils getRequire should create a require statement 1`] = `"const filesys = require(\\"fs\\");"`; + +exports[`utils isAssignment should allow custom transform functions instead of singularProperty 1`] = ` +"module.exports = { + plugins: [one, two, three] +}" +`; + +exports[`utils isAssignment should invoke a callback if parent type is AssignmentExpression 1`] = ` +"module.exports = { + context: Heyho +}" +`; + +exports[`utils pushCreateProperty should create an object or property and push the value to a node 1`] = ` +"module.exports = { + pushMe: { + just: pushed + } + }" +`; diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index d048272c948..2744d065646 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -341,16 +341,16 @@ function createArrayWithChildren(j, key, subProps, shouldDropKeys) { } /* -* @function createPropertyWithSuppliedProperty +* @function createObjectWithSuppliedProperty * -* Creates an property with an supplied property as parameter +* Creates an object with an supplied property as parameter * @param j — jscodeshift API * @param { String } key - object name * @param { Node } prop - property to be added * @returns - { Node } - An property with the supplied property */ -function createPropertyWithSuppliedProperty(j, key, prop) { +function createObjectWithSuppliedProperty(j, key, prop) { return j.property('init', j.identifier(key), prop); } @@ -387,7 +387,7 @@ function pushCreateProperty(j, p, key, val) { } return p.value.properties.push( - createPropertyWithSuppliedProperty(j, key, property) + createObjectWithSuppliedProperty(j, key, property) ); } @@ -406,6 +406,31 @@ function createSingularProperty(j, p, name, webpackProperties) { return pushCreateProperty(j, p, name, webpackProperties[name]); } +/* +* @function isAssignment +* +* Checks if we are at the correct node and later invokes a callback +* for the transforms to either use their own transform function or +* use createSingularProperty if the transform doesn't expect any properties +* @param j — jscodeshift API +* @param { Node } p - Node to push against +* @param { Function } cb - callback to be invoked +* @param { String } identifier - key to use as property +* @param { Object } property - WebpackOptions that later will be converted via +* createSingularProperty via WebpackOptions[identifier] +* @returns - { Function } cb - Returns the callback and pushes a new node +*/ + +function isAssignment(j, p, cb, identifier, property) { + if(p.parent.value.type === 'AssignmentExpression') { + if(j) { + return cb(j, p, identifier, property); + } + else { + return cb(p); + } + } +} module.exports = { safeTraverse, @@ -422,8 +447,9 @@ module.exports = { checkIfExistsAndAddValue, createArrayWithChildren, createEmptyArrayProperty, - createPropertyWithSuppliedProperty, + createObjectWithSuppliedProperty, createExternalRegExp, pushCreateProperty, - createSingularProperty + createSingularProperty, + isAssignment }; diff --git a/lib/transformations/utils.test.js b/lib/transformations/utils.test.js index 7b0b3d8bdfd..b67e3d201a7 100644 --- a/lib/transformations/utils.test.js +++ b/lib/transformations/utils.test.js @@ -197,4 +197,105 @@ var a = { plugs: [] } expect(ast.toSource()).toMatchSnapshot(); }); }); + describe('createArrayWithChildren', () => { + it('should find an prop that matches key and create an array with it', () => { + const ast = j('{}'); + let key = 'react'; + let reactArr = { + react: [ '\'bo\''] + }; + const arr = utils.createArrayWithChildren(j, key, reactArr, false); + ast.find(j.Program).forEach(node => j(node).replaceWith(arr)); + expect(ast.toSource()).toMatchSnapshot(); + }); + it('should add all children of an array to a new one with a supplied key', () => { + const ast = j('{}'); + let key = 'myVeryOwnKey'; + let helloWorldArray = [ '\'hello\'', 'world']; + const arr = utils.createArrayWithChildren(j, key, helloWorldArray, true); + ast.find(j.Program).forEach(node => j(node).replaceWith(arr)); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); + describe('createEmptyArrayProperty', () => { + it('should create an array with no properties', () => { + const ast = j('{}'); + const arr = utils.createEmptyArrayProperty(j, 'its-lit'); + ast.find(j.Program).forEach(node => j(node).replaceWith(arr)); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); + + describe('createObjectWithSuppliedProperty', () => { + it('should create an object with a property supplied by us', () => { + const ast = j('{}'); + const prop = utils.createObjectWithSuppliedProperty(j, 'its-lit', j.objectExpression([])); + ast.find(j.Program).forEach(node => j(node).replaceWith(prop)); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); + describe('createExternalRegExp', () => { + it('should create an regExp property that has been parsed by jscodeshift', () => { + const ast = j('{}'); + const reg = j('\'\t\''); + const prop = utils.createExternalRegExp(j, reg); + ast.find(j.Program).forEach(node => j(node).replaceWith(prop)); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); + describe('pushCreateProperty', () => { + it('should create an object or property and push the value to a node', () => { + const ast = j(`module.exports = { + pushMe: {} + }`); + ast.find(j.Identifier).filter(n => n.value.name === 'pushMe').forEach(node => { + const heavyNodeNoSafeTraverse = node.parentPath.value; + utils.pushCreateProperty(j, heavyNodeNoSafeTraverse, 'just', 'pushed'); + }); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); + describe('createSingularProperty', () => { + it('should create an single property with no nested properties', () => { + const ast = j('module.exports = {}'); + const myObj = { + context: 'Heyho' + }; + const myKey = 'context'; + + ast.find(j.ObjectExpression) + .filter(n => n.parent.value.type === 'AssignmentExpression') + .forEach(node => { + utils.createSingularProperty(j, node, myKey, myObj); + }); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); + describe('isAssignment', () => { + it('should invoke a callback if parent type is AssignmentExpression', () => { + const ast = j('module.exports = {}'); + const myObj = { + context: 'Heyho' + }; + const myKey = 'context'; + + ast.find(j.ObjectExpression) + .filter(n => utils.isAssignment(j, n, utils.createSingularProperty, myKey, myObj)); + expect(ast.toSource()).toMatchSnapshot(); + }); + it('should allow custom transform functions instead of singularProperty', () => { + const ast = j('module.exports = {}'); + + function createPluginsProperty(p) { + const webpackProperties = { + plugins: ['one', 'two', 'three'] + }; + const pluginArray = utils.createArrayWithChildren(j, 'plugins', webpackProperties); + return p.value.properties.push(pluginArray); + } + ast.find(j.ObjectExpression) + .filter(n => utils.isAssignment(null, n, createPluginsProperty)); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); }); From c563328e0a4c35a13bfc37449ed3a76e6fa819b0 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 23 Apr 2017 16:30:04 +0200 Subject: [PATCH 067/101] fix: don't use await for promise --- lib/utils/npm-exists.spec.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/lib/utils/npm-exists.spec.js b/lib/utils/npm-exists.spec.js index b192127a4be..be5ba3d7c96 100644 --- a/lib/utils/npm-exists.spec.js +++ b/lib/utils/npm-exists.spec.js @@ -1,16 +1,17 @@ -/* eslint node/no-unsupported-features: 0 */ 'use strict'; const exists = require('./npm-exists'); -describe('exists', () => { +describe('npm-exists', () => { - it('should sucessfully existence of a published module', async () => { - let itExists = await exists('webpack-addons-ylvis'); - expect(itExists).toBe(true); + it('should sucessfully existence of a published module', () => { + exists('webpack-addons-ylvis').then( (status) => { + expect(status).toBe(true); + }); }); - it('should return false for the existence of a fake module', async () => { - let itExists = await exists('webpack-addons-noop'); - expect(itExists).toBe(false); + it('should return false for the existence of a fake module', () => { + exists('webpack-addons-noop').then( (status) => { + expect(status).toBe(false); + }); }); }); From 44ce0d6954759a1669092c82e3ccb9c753a11ce3 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 23 Apr 2017 18:07:29 +0200 Subject: [PATCH 068/101] enhancements: send each transform object to respective transform --- .../transformations/context/context.js | 8 ++--- .../transformations/context/context.test.js | 6 ++-- .../transformations/devtool/devtool.js | 7 ++-- .../transformations/devtool/devtool.test.js | 8 ++--- lib/creator/transformations/entry/entry.js | 9 +++-- .../transformations/entry/entry.test.js | 14 ++++---- .../transformations/externals/externals.js | 33 +++++++++-------- .../externals/externals.test.js | 32 ++++++++--------- lib/creator/transformations/index.js | 19 +++++++--- lib/creator/transformations/module/module.js | 17 +++++---- .../transformations/module/module.test.js | 8 ++--- lib/creator/transformations/module/utils.js | 2 +- lib/creator/transformations/node/node.js | 11 +++--- lib/creator/transformations/node/node.test.js | 4 +-- lib/creator/transformations/other/amd.js | 11 +++--- lib/creator/transformations/other/bail.js | 7 ++-- lib/creator/transformations/other/cache.js | 7 ++-- lib/creator/transformations/other/merge.js | 11 +++--- .../transformations/other/other.test.js | 12 +++---- lib/creator/transformations/other/profile.js | 7 ++-- lib/creator/transformations/output/output.js | 15 ++++---- .../transformations/output/output.test.js | 4 +-- .../performance/performance.js | 11 +++--- .../performance/performance.test.js | 4 +-- .../transformations/plugins/plugins.js | 9 +++-- .../transformations/plugins/plugins.test.js | 4 +-- .../transformations/resolve/resolve.js | 35 +++++++++---------- .../transformations/resolve/resolve.test.js | 4 +-- lib/creator/transformations/stats/stats.js | 19 +++++----- .../transformations/stats/stats.test.js | 6 ++-- lib/creator/transformations/target/target.js | 10 +++--- .../transformations/target/target.test.js | 4 +-- .../transformations/top-scope/top-scope.js | 5 ++- .../top-scope/top-scope.test.js | 4 +-- lib/creator/transformations/watch/watch.js | 10 +++--- .../transformations/watch/watch.test.js | 8 ++--- .../transformations/watch/watchOptions.js | 11 +++--- .../watch/watchOptions.test.js | 12 +++---- lib/transformations/defineTest.js | 11 ++---- lib/transformations/utils.js | 3 +- lib/transformations/utils.test.js | 8 ++--- 41 files changed, 204 insertions(+), 226 deletions(-) diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 7bf7aadea41..ab452c0bfa5 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -9,14 +9,12 @@ const createSingularProperty = require('../../../transformations/utils').createS * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; - - if(webpackProperties['context']) { +module.exports = function(j, ast, webpackProperties) { + if(webpackProperties) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(j, p, createSingularProperty, 'context', webpackProperties)); } else { diff --git a/lib/creator/transformations/context/context.test.js b/lib/creator/transformations/context/context.test.js index 935a0c09239..0258c5528de 100644 --- a/lib/creator/transformations/context/context.test.js +++ b/lib/creator/transformations/context/context.test.js @@ -1,5 +1,5 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'context', 'context-0', {context : 'path.resolve(__dirname, "app")'}); -defineTest(__dirname, 'context', 'context-1', {context : '\'./some/fake/path\''}); -defineTest(__dirname, 'context', 'context-2', {context : 'contextVariable'}); +defineTest(__dirname, 'context', 'context-0', 'path.resolve(__dirname, "app")'); +defineTest(__dirname, 'context', 'context-1', '\'./some/fake/path\''); +defineTest(__dirname, 'context', 'context-2', 'contextVariable'); diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index ca555d9fae6..772254aa4e6 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -9,14 +9,13 @@ const createSingularProperty = require('../../../transformations/utils').createS * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { - if(webpackProperties['devtool']) { + if(webpackProperties) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(j, p, createSingularProperty, 'devtool', webpackProperties)); } else { diff --git a/lib/creator/transformations/devtool/devtool.test.js b/lib/creator/transformations/devtool/devtool.test.js index 59b01a1d92b..01f574301a5 100644 --- a/lib/creator/transformations/devtool/devtool.test.js +++ b/lib/creator/transformations/devtool/devtool.test.js @@ -1,6 +1,6 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'devtool', 'devtool-0', {devtool : '\'source-map\''}); -defineTest(__dirname, 'devtool', 'devtool-0', {devtool : 'myVariable'}); -defineTest(__dirname, 'devtool', 'devtool-1', {devtool : '\'cheap-module-source-map\''}); -defineTest(__dirname, 'devtool', 'devtool-1', {devtool : 'false'}); +defineTest(__dirname, 'devtool', 'devtool-0', '\'source-map\''); +defineTest(__dirname, 'devtool', 'devtool-0', 'myVariable'); +defineTest(__dirname, 'devtool', 'devtool-1', '\'cheap-module-source-map\''); +defineTest(__dirname, 'devtool', 'devtool-1', 'false'); diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index ef9a194d3bb..c602856f1a0 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -9,13 +9,12 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function addEntryPoints(entries) { @@ -42,9 +41,9 @@ module.exports = function(j, ast, yeomanConfig) { entryNode.push( j.property( 'init', utils.createIdentifierOrLiteral(j, 'entry'), - addEntryPoints(webpackProperties['entry']))); + addEntryPoints(webpackProperties))); } - if(webpackProperties['entry']) { + if(webpackProperties) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(null, p, createEntryProperty)); } else { diff --git a/lib/creator/transformations/entry/entry.test.js b/lib/creator/transformations/entry/entry.test.js index 8252e5931d6..bad451e36a2 100644 --- a/lib/creator/transformations/entry/entry.test.js +++ b/lib/creator/transformations/entry/entry.test.js @@ -1,11 +1,11 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'entry', 'entry-0', {entry: '\'index.js\''}); -defineTest(__dirname, 'entry', 'entry-0', {entry: ['\'index.js\'', '\'app.js\'']}); -defineTest(__dirname, 'entry', 'entry-0', {entry: { +defineTest(__dirname, 'entry', 'entry-0', '\'index.js\''); +defineTest(__dirname, 'entry', 'entry-0', ['\'index.js\'', '\'app.js\'']); +defineTest(__dirname, 'entry', 'entry-0', { index: '\'index.js\'', app: '\'app.js\'' -}}); -defineTest(__dirname, 'entry', 'entry-0', {entry: '() => \'index.js\''}); -defineTest(__dirname, 'entry', 'entry-0', {entry: '() => new Promise((resolve) => resolve([\'./app\', \'./router\']))'}); -defineTest(__dirname, 'entry', 'entry-0', {entry: 'entryStringVariable'}); +}); +defineTest(__dirname, 'entry', 'entry-0', '() => \'index.js\''); +defineTest(__dirname, 'entry', 'entry-0', '() => new Promise((resolve) => resolve([\'./app\', \'./router\']))'); +defineTest(__dirname, 'entry', 'entry-0', 'entryStringVariable'); diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index f4cf7aa473e..3059b838a33 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -8,19 +8,18 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createExternalProperty(p) { - if(webpackProperties.externals instanceof RegExp || typeof(webpackProperties.externals) === 'string') { - return utils.pushCreateProperty(j, p, 'externals', webpackProperties.externals); + if(webpackProperties instanceof RegExp || typeof(webpackProperties) === 'string') { + return utils.pushCreateProperty(j, p, 'externals', webpackProperties); } - else if(Array.isArray(webpackProperties.externals)) { + else if(Array.isArray(webpackProperties)) { const externalArray = utils.createEmptyArrayProperty(j, 'externals'); - webpackProperties.externals.forEach( (n) => { + webpackProperties.forEach( (n) => { // [{myprop: 'hello'}] let objectOfArray = j.objectExpression([]); if(typeof(n) !== 'string') { @@ -44,17 +43,17 @@ module.exports = function(j, ast, yeomanConfig) { externalsProp.filter(n => (utils.safeTraverse(n, ['key', 'name']) === 'externals') ).forEach( (prop) => { - Object.keys(webpackProperties['externals']).forEach( (webpackProp) => { - if(Array.isArray(webpackProperties.externals[webpackProp])) { + Object.keys(webpackProperties).forEach( (webpackProp) => { + if(Array.isArray(webpackProperties[webpackProp])) { // if we got a type, we make it an array const externalArray = utils.createArrayWithChildren( - j, webpackProp, webpackProperties.externals[webpackProp], true + j, webpackProp, webpackProperties[webpackProp], true ); prop.value.properties.push(externalArray); } - else if(typeof(webpackProperties.externals[webpackProp]) === 'string') { + else if(typeof(webpackProperties[webpackProp]) === 'string') { utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties.externals[webpackProp] + j, prop, webpackProp, webpackProperties[webpackProp] ); } else { @@ -66,15 +65,15 @@ module.exports = function(j, ast, yeomanConfig) { (utils.safeTraverse(n, ['key', 'name']) === webpackProp) ) .forEach( (externalProp) => { - Object.keys(webpackProperties.externals[webpackProp]).forEach( (subProps) => { - if(Array.isArray(webpackProperties.externals[webpackProp][subProps])) { + Object.keys(webpackProperties[webpackProp]).forEach( (subProps) => { + if(Array.isArray(webpackProperties[webpackProp][subProps])) { const subExternalArray = utils.createArrayWithChildren( - j, subProps, webpackProperties.externals[webpackProp][subProps], true + j, subProps, webpackProperties[webpackProp][subProps], true ); externalProp.value.properties.push(subExternalArray); } else { utils.pushCreateProperty( - j, externalProp, subProps, webpackProperties.externals[webpackProp][subProps] + j, externalProp, subProps, webpackProperties[webpackProp][subProps] ); } }); @@ -84,7 +83,7 @@ module.exports = function(j, ast, yeomanConfig) { }); } } - if(webpackProperties['externals']) { + if(webpackProperties) { return ast.find(j.ObjectExpression) .filter(p => utils.safeTraverse(p , ['parent', 'value', 'left', 'property', 'name']) === 'exports') .forEach(createExternalProperty); diff --git a/lib/creator/transformations/externals/externals.test.js b/lib/creator/transformations/externals/externals.test.js index 9940e02c417..07331dda65a 100644 --- a/lib/creator/transformations/externals/externals.test.js +++ b/lib/creator/transformations/externals/externals.test.js @@ -1,40 +1,40 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'externals', 'externals-0', {externals: /react/}); -defineTest(__dirname, 'externals', 'externals-1', {externals: { +defineTest(__dirname, 'externals', 'externals-0', /react/); +defineTest(__dirname, 'externals', 'externals-1', { jquery: '\'jQuery\'', react: '\'react\'' -}}); +}); -defineTest(__dirname, 'externals', 'externals-1', {externals: 'myObj'}); +defineTest(__dirname, 'externals', 'externals-1', 'myObj'); -defineTest(__dirname, 'externals', 'externals-1', {externals: { +defineTest(__dirname, 'externals', 'externals-1', { jquery: '\'jQuery\'', react: 'reactObj' -}}); +}); -defineTest(__dirname, 'externals', 'externals-1', {externals: { +defineTest(__dirname, 'externals', 'externals-1', { jquery: '\'jQuery\'', react: ['reactObj', 'path.join(__dirname, \'app\')', '\'jquery\''] -}}); +}); -defineTest(__dirname, 'externals', 'externals-1', {externals: { +defineTest(__dirname, 'externals', 'externals-1', { lodash: { commonjs: '\'lodash\'', amd: '\'lodash\'', root: '\'_\'' } -}}); +}); -defineTest(__dirname, 'externals', 'externals-1', {externals: { +defineTest(__dirname, 'externals', 'externals-1', { lodash: { commonjs: 'lodash', amd: 'hidash', root: '_' } -}}); +}); -defineTest(__dirname, 'externals', 'externals-1', {externals: [ +defineTest(__dirname, 'externals', 'externals-1', [ { a: 'false', b: 'true', @@ -47,9 +47,9 @@ defineTest(__dirname, 'externals', 'externals-1', {externals: [ 'callback();' + '}' ] -}); +); -defineTest(__dirname, 'externals', 'externals-1', {externals: [ +defineTest(__dirname, 'externals', 'externals-1', [ 'myObj', 'function(context, request, callback) {' + 'if (/^yourregex$/.test(request)){' + @@ -58,4 +58,4 @@ defineTest(__dirname, 'externals', 'externals-1', {externals: [ 'callback();' + '}' ] -}); +); diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index e0cee855322..617f45e6827 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -60,12 +60,21 @@ const transformsObject = { mergeTransform }; -module.exports = function runTransform(yeomanConfig) { - const transformations = Object.keys(transformsObject).map(k => transformsObject[k]); - Object.keys(yeomanConfig).forEach( (scaffoldPiece) => { - const config = yeomanConfig[scaffoldPiece]; +module.exports = function runTransform(webpackProperties) { + Object.keys(webpackProperties).forEach( (scaffoldPiece) => { + const config = webpackProperties[scaffoldPiece]; + const transformations = Object.keys(transformsObject).map(k => { + const stringVal = k.substr(0, k.indexOf('Transform')); + if(config.webpackOptions[stringVal]) { + return [transformsObject[k], config.webpackOptions[stringVal]]; + } else { + return [transformsObject[k], config[stringVal]]; + } + }); let ast = j('module.exports = {}'); - return pEachSeries(transformations, f => f(j, ast, config)) + return pEachSeries(transformations, f => { + return f[0](j, ast, f[1]); + }) .then(() => { const outputPath = process.cwd() + '/webpack.' + (config.configName ? config.configName : 'config') + '.js'; diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index 04164f7db0b..a61e6eb3499 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -11,12 +11,11 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createModuleProperties(p) { utils.pushCreateProperty(j, p, 'module', j.objectExpression([])); @@ -24,19 +23,19 @@ module.exports = function(j, ast, yeomanConfig) { moduleNode.filter(n => (utils.safeTraverse(n, ['key', 'name']) === 'module') ).forEach( (prop) => { - Object.keys(webpackProperties['module']) + Object.keys(webpackProperties) .forEach( (webpackProp) => { if(['noParse', 'rules'].includes(webpackProp)) { - if(webpackProperties.module[webpackProp].__paths) { + if(webpackProperties[webpackProp].__paths) { // optional if user can't use regular regexp localUtils.regExpStrategy(j, webpackProperties, webpackProp, prop); } - else if(Array.isArray(webpackProperties.module[webpackProp])) { + else if(Array.isArray(webpackProperties[webpackProp])) { const rulesArray = utils.createEmptyArrayProperty(j, webpackProp); prop.value.properties.push(rulesArray); // Keeps track of what object we're refering to when adding props let seen = -1; - let rulesProperties = webpackProperties.module[webpackProp]; + let rulesProperties = webpackProperties[webpackProp]; rulesProperties .forEach( (subProps) => { @@ -100,14 +99,14 @@ module.exports = function(j, ast, yeomanConfig) { }); } else { return utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties.module[webpackProp] + j, prop, webpackProp, webpackProperties[webpackProp] ); } } }); }); } - if(!webpackProperties['module']) { + if(!webpackProperties) { return ast; } else { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/module/module.test.js b/lib/creator/transformations/module/module.test.js index b6e81827d6b..c2838abebc0 100644 --- a/lib/creator/transformations/module/module.test.js +++ b/lib/creator/transformations/module/module.test.js @@ -1,6 +1,6 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'module', 'module-0', {module: { +defineTest(__dirname, 'module', 'module-0', { rules: [{ test: new RegExp(/\.(js|vue)$/), loader: '\'eslint-loader\'', @@ -33,9 +33,9 @@ defineTest(__dirname, 'module', 'module-0', {module: { someArr: ['Hey'] } }] -}}); +}); -defineTest(__dirname, 'module', 'module-1', {module: { +defineTest(__dirname, 'module', 'module-1', { noParse: /jquery|lodash/, rules: [{ test: new RegExp(/\.js$/), @@ -43,4 +43,4 @@ defineTest(__dirname, 'module', 'module-1', {module: { amd: false } }] -}}); +}); diff --git a/lib/creator/transformations/module/utils.js b/lib/creator/transformations/module/utils.js index b0865ea824d..39a3babaced 100644 --- a/lib/creator/transformations/module/utils.js +++ b/lib/creator/transformations/module/utils.js @@ -43,7 +43,7 @@ function createUseProperties(j, key, subProps) { Object.keys(subProps[key]).forEach( (optionProperty) => { if(typeof(subProps[key][optionProperty]) === 'string') { useVal.value.elements.push( - utils.createIdentifierOrLiteral(subProps[key][optionProperty]) + utils.createIdentifierOrLiteral(j, subProps[key][optionProperty]) ); } else { let loaderProperty = j.objectExpression([]); diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index 66aee1c0ac5..bc92fe0941e 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -9,12 +9,11 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createNodeProperty(p) { utils.pushCreateProperty(j, p, 'node', j.objectExpression([])); @@ -22,14 +21,14 @@ module.exports = function(j, ast, yeomanConfig) { node.filter(n => (utils.safeTraverse(n, ['key', 'name']) === 'node') ).forEach( (prop) => { - Object.keys(webpackProperties.node).forEach( (webpackProp) => { + Object.keys(webpackProperties).forEach( (webpackProp) => { utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties.node[webpackProp] + j, prop, webpackProp, webpackProperties[webpackProp] ); }); }); } - if(webpackProperties['node']) { + if(webpackProperties) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(null, p, createNodeProperty)); } else { diff --git a/lib/creator/transformations/node/node.test.js b/lib/creator/transformations/node/node.test.js index bd1b0e0484b..53cf24e541a 100644 --- a/lib/creator/transformations/node/node.test.js +++ b/lib/creator/transformations/node/node.test.js @@ -1,6 +1,6 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'node', 'node-0', {node : { +defineTest(__dirname, 'node', 'node-0', { console: false, global: true, process: true, @@ -8,4 +8,4 @@ defineTest(__dirname, 'node', 'node-0', {node : { __filename: 'mock', __dirname: 'mock', setImmediate: true -}}); +}); diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index b9e86ad922c..167f062155b 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -9,26 +9,25 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createAMDProperty(p) { utils.pushCreateProperty(j, p, 'amd', j.objectExpression([])); let amdNode = p.value.properties; amdNode.filter(n => (utils.safeTraverse(n, ['key', 'name']) === 'amd') ).forEach( (prop) => { - Object.keys(webpackProperties['amd']).forEach( (webpackProp) => { + Object.keys(webpackProperties).forEach( (webpackProp) => { utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties.amd[webpackProp] + j, prop, webpackProp, webpackProperties[webpackProp] ); }); }); } - if(webpackProperties['amd'] && typeof(webpackProperties['amd']) === 'object') { + if(webpackProperties && typeof(webpackProperties) === 'object') { return ast.find(j.ObjectExpression) .filter(p => isAssignment(null, p, createAMDProperty)); } else { diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index 2cbc03df7b7..1950eaa1dd6 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -9,14 +9,13 @@ const createSingularProperty = require('../../../transformations/utils').createS * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { - if(webpackProperties['bail']) { + if(webpackProperties) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(j, p, createSingularProperty, 'bail', webpackProperties)); } else { diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index 5c4fe10a534..e9d88931420 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -9,14 +9,13 @@ const createSingularProperty = require('../../../transformations/utils').createS * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { - if(webpackProperties['cache']) { + if(webpackProperties) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(j, p, createSingularProperty, 'cache', webpackProperties)); } else { diff --git a/lib/creator/transformations/other/merge.js b/lib/creator/transformations/other/merge.js index e17bc74c75b..6dad50f1f4a 100644 --- a/lib/creator/transformations/other/merge.js +++ b/lib/creator/transformations/other/merge.js @@ -8,12 +8,11 @@ const isAssignment = require('../../../transformations/utils').isAssignment; * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createMergeProperty(p) { // FIXME Use j.callExp() let exportsDecl = p.value.body.map( (n) => { @@ -35,12 +34,12 @@ module.exports = function(j, ast, yeomanConfig) { }, right: j.callExpression( j.identifier('merge'), - [j.identifier(webpackProperties['merge']), exportsDecl.pop()]) + [j.identifier(webpackProperties), exportsDecl.pop()]) }; p.value.body[bodyLength - 1] = newVal; } - if(webpackProperties['merge']) { - return ast.find(j.Program).filter(p => isAssignment(p, createMergeProperty)); + if(webpackProperties) { + return ast.find(j.Program).filter(p => isAssignment(null, p, createMergeProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/other.test.js b/lib/creator/transformations/other/other.test.js index de593101e1b..bec70af6831 100644 --- a/lib/creator/transformations/other/other.test.js +++ b/lib/creator/transformations/other/other.test.js @@ -1,10 +1,10 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'amd', 'other-0', {amd : { +defineTest(__dirname, 'amd', 'other-0', { jQuery: true, kQuery: false} -}); -defineTest(__dirname, 'bail', 'other-0', {bail : true}); -defineTest(__dirname, 'cache', 'other-0', {cache : true}); -defineTest(__dirname, 'cache', 'other-0', {cache : 'cacheVal'}); -defineTest(__dirname, 'profile', 'other-0', {profile : true}); +); +defineTest(__dirname, 'bail', 'other-0', true); +defineTest(__dirname, 'cache', 'other-0', true); +defineTest(__dirname, 'cache', 'other-0', 'cacheVal'); +defineTest(__dirname, 'profile', 'other-0', true); diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index dfa87b867d8..30f7b55717e 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -9,13 +9,12 @@ const createSingularProperty = require('../../../transformations/utils').createS * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; - if(webpackProperties['profile']) { +module.exports = function(j, ast, webpackProperties) { + if(webpackProperties) { return ast.find(j.ObjectExpression) .filter(p => isAssignment(j, p, createSingularProperty, 'profile', webpackProperties)); } else { diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index e0b418ac1b0..3113f4c5b25 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -10,34 +10,33 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createOutputProperties(p) { utils.pushCreateProperty(j, p, 'output', j.objectExpression([])); let outputNode = p.value.properties; outputNode.filter( n => (utils.safeTraverse(n, ['key', 'name']) === 'output') ).forEach( (prop) => { - Object.keys(webpackProperties.output).forEach( (webpackProp) => { + Object.keys(webpackProperties).forEach( (webpackProp) => { if(webpackOutputTypes.includes(webpackProp)) { - if(webpackProperties.output[webpackProp].__paths) { - let regExpProp = utils.createExternalRegExp(j, webpackProperties.output[webpackProp]); + if(webpackProperties[webpackProp].__paths) { + let regExpProp = utils.createExternalRegExp(j, webpackProperties[webpackProp]); utils.pushCreateProperty(j, prop, webpackProp, regExpProp); } else { utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties.output[webpackProp] + j, prop, webpackProp, webpackProperties[webpackProp] ); } } }); }); } - if(webpackProperties['output']) { + if(webpackProperties) { return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createOutputProperties)); } else { return ast; diff --git a/lib/creator/transformations/output/output.test.js b/lib/creator/transformations/output/output.test.js index bbe83bf8394..413ead9c291 100644 --- a/lib/creator/transformations/output/output.test.js +++ b/lib/creator/transformations/output/output.test.js @@ -1,7 +1,7 @@ const defineTest = require('../../../transformations/defineTest'); const jscodeshift = require('jscodeshift'); -defineTest(__dirname, 'output', 'output-0', {output: { +defineTest(__dirname, 'output', 'output-0', { filename: '\'bundle\'', path: '\'dist/assets\'', pathinfo: true, @@ -10,4 +10,4 @@ defineTest(__dirname, 'output', 'output-0', {output: { sourcePrefix: jscodeshift('\'\t\''), umdNamedDefine: true, strictModuleExceptionHandling: true -}}); +}); diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 80dbb98fd69..9b8bc241e32 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -10,12 +10,11 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createPerformanceProperty(p) { @@ -24,16 +23,16 @@ module.exports = function(j, ast, yeomanConfig) { performanceNode.filter(n => (utils.safeTraverse(n, ['key', 'name']) === 'performance') ).forEach( (prop) => { - Object.keys(webpackProperties.performance).forEach( (webpackProp) => { + Object.keys(webpackProperties).forEach( (webpackProp) => { if(performanceTypes.includes(webpackProp)) { utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties.performance[webpackProp] + j, prop, webpackProp, webpackProperties[webpackProp] ); } }); }); } - if(webpackProperties['performance'] && typeof(webpackProperties['performance']) === 'object') { + if(webpackProperties && typeof(webpackProperties) === 'object') { return ast.find(j.ObjectExpression) .filter(p => isAssignment(null, p, createPerformanceProperty)); } else { diff --git a/lib/creator/transformations/performance/performance.test.js b/lib/creator/transformations/performance/performance.test.js index 0eca6e8ed00..0e078cb5d24 100644 --- a/lib/creator/transformations/performance/performance.test.js +++ b/lib/creator/transformations/performance/performance.test.js @@ -1,10 +1,10 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'performance', 'performance-0', {performance: { +defineTest(__dirname, 'performance', 'performance-0', { hints: '\'warning\'', maxEntrypointSize: 400000, maxAssetSize: 100000, assetFilter: 'function(assetFilename) {' + 'return assetFilename.endsWith(\'.js\');' + '}' -}}); +}); diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index 4e129205461..c937487ae8a 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -8,17 +8,16 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createPluginsProperty(p) { - const pluginArray = utils.createArrayWithChildren(j, 'plugins', webpackProperties); + const pluginArray = utils.createArrayWithChildren(j, 'plugins', webpackProperties, true); return p.value.properties.push(pluginArray); } - if(webpackProperties['plugins'] && Array.isArray(webpackProperties['plugins'])) { + if(webpackProperties && Array.isArray(webpackProperties)) { return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createPluginsProperty)); } else { return ast; diff --git a/lib/creator/transformations/plugins/plugins.test.js b/lib/creator/transformations/plugins/plugins.test.js index 5825f2a52dd..dde8d0ae2d5 100644 --- a/lib/creator/transformations/plugins/plugins.test.js +++ b/lib/creator/transformations/plugins/plugins.test.js @@ -1,5 +1,5 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'plugins', 'plugins-0', {plugins : [ +defineTest(__dirname, 'plugins', 'plugins-0', [ 'new webpack.optimize.CommonsChunkPlugin({name:' + '\'' + 'vendor' + '\'' + ',filename:' + '\'' + 'vendor' + '-[hash].min.js\'})' -]}); +]); diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index 1baeaaf6204..d5f4a39b9a7 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -9,28 +9,27 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createResolveProperties(p) { utils.pushCreateProperty(j, p, 'resolve', j.objectExpression([])); let resolveNode = p.value.properties; resolveNode.filter(n => n.key.name === 'resolve').forEach( (prop) => { - Object.keys(webpackProperties.resolve).forEach( (webpackProp) => { + Object.keys(webpackProperties).forEach( (webpackProp) => { if(resolveTypes.includes(webpackProp) || webpackProp === 'resolveLoader') { - if(Array.isArray(webpackProperties.resolve[webpackProp])) { + if(Array.isArray(webpackProperties[webpackProp])) { // if we got a type, we make it an array const resolveArray = utils.createArrayWithChildren( - j, webpackProp, webpackProperties.resolve[webpackProp], true + j, webpackProp, webpackProperties[webpackProp], true ); prop.value.properties.push(resolveArray); } - else if(typeof(webpackProperties.resolve[webpackProp]) === 'boolean') { + else if(typeof(webpackProperties[webpackProp]) === 'boolean') { utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties.resolve[webpackProp] + j, prop, webpackProp, webpackProperties[webpackProp] ); } else { @@ -39,26 +38,26 @@ module.exports = function(j, ast, yeomanConfig) { if(resolveProp.key.name === webpackProp) { if(resolveProp.key.name === 'cachePredicate') { let cachePredicateVal = - (typeof webpackProperties.resolve[webpackProp] === 'string') ? - j.identifier(webpackProperties.resolve[webpackProp]) : - j.literal(webpackProperties.resolve[webpackProp]); + (typeof webpackProperties[webpackProp] === 'string') ? + j.identifier(webpackProperties[webpackProp]) : + j.literal(webpackProperties[webpackProp]); resolveProp.value = cachePredicateVal; } - Object.keys(webpackProperties.resolve[webpackProp]).forEach( (aliasProps) => { - if(Array.isArray(webpackProperties.resolve[webpackProp][aliasProps])) { + Object.keys(webpackProperties[webpackProp]).forEach( (aliasProps) => { + if(Array.isArray(webpackProperties[webpackProp][aliasProps])) { const resolveLoaderArray = utils.createArrayWithChildren( - j, aliasProps, webpackProperties.resolve[webpackProp][aliasProps], true + j, aliasProps, webpackProperties[webpackProp][aliasProps], true ); resolveProp.value.properties.push(resolveLoaderArray); - } else if(webpackProperties.resolve[webpackProp][aliasProps].length > 1) { + } else if(webpackProperties[webpackProp][aliasProps].length > 1) { if(aliasProps.indexOf('inject') >= 0) { resolveProp.value.properties.push(j.identifier( - webpackProperties.resolve[webpackProp][aliasProps] + webpackProperties[webpackProp][aliasProps] )); } else { utils.pushCreateProperty( - j, resolveProp, aliasProps, webpackProperties.resolve[webpackProp][aliasProps] + j, resolveProp, aliasProps, webpackProperties[webpackProp][aliasProps] ); } } @@ -70,7 +69,7 @@ module.exports = function(j, ast, yeomanConfig) { }); }); } - if(webpackProperties['resolve'] ) { + if(webpackProperties) { return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createResolveProperties)); } else { diff --git a/lib/creator/transformations/resolve/resolve.test.js b/lib/creator/transformations/resolve/resolve.test.js index 95e21123020..9b6742fa13c 100644 --- a/lib/creator/transformations/resolve/resolve.test.js +++ b/lib/creator/transformations/resolve/resolve.test.js @@ -1,6 +1,6 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'resolve', 'resolve-0', {resolve: { +defineTest(__dirname, 'resolve', 'resolve-0', { alias: { hello: '\'world\'', world: 'hello' @@ -22,4 +22,4 @@ defineTest(__dirname, 'resolve', 'resolve-0', {resolve: { }, plugins: ['somePlugin', '\'stringVal\''], symlinks: true -}}); +}); diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index 6ac506fc5fa..dacd3f0f6ca 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -9,29 +9,28 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createStatsProperty(p) { utils.pushCreateProperty(j, p, 'stats', j.objectExpression([])); let statsNode = p.value.properties; statsNode.filter(n => (utils.safeTraverse(n, ['key', 'name']) === 'stats') ).forEach( (prop) => { - Object.keys(webpackProperties.stats).forEach( (webpackProp) => { + Object.keys(webpackProperties).forEach( (webpackProp) => { if(statsTypes.includes(webpackProp)) { - if(Array.isArray(webpackProperties.stats[webpackProp])) { + if(Array.isArray(webpackProperties[webpackProp])) { const statsArray = utils.createArrayWithChildren( - j, webpackProp, webpackProperties.stats[webpackProp], true + j, webpackProp, webpackProperties[webpackProp], true ); prop.value.properties.push(statsArray); } else { utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties.stats[webpackProp] + j, prop, webpackProp, webpackProperties[webpackProp] ); } } else { @@ -40,15 +39,15 @@ module.exports = function(j, ast, yeomanConfig) { }); }); } - if(webpackProperties['stats'] && typeof(webpackProperties['stats']) === 'object') { + if(webpackProperties && typeof(webpackProperties) === 'object') { return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createStatsProperty)); } // FIXME -> HOC AssignmentExpression - else if(webpackProperties['stats'] && webpackProperties['stats'].length) { + else if(webpackProperties && webpackProperties.length) { return ast.find(j.ObjectExpression).filter(p => { if(p.parent.value.type === 'AssignmentExpression') { return p.value.properties.push( - j.property('init', j.identifier('stats'), j.identifier(webpackProperties['stats'])) + j.property('init', j.identifier('stats'), j.identifier(webpackProperties)) ); } }); diff --git a/lib/creator/transformations/stats/stats.test.js b/lib/creator/transformations/stats/stats.test.js index 8a6b5a7a91d..432eac37522 100644 --- a/lib/creator/transformations/stats/stats.test.js +++ b/lib/creator/transformations/stats/stats.test.js @@ -1,6 +1,6 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'stats', 'stats-0', {stats: { +defineTest(__dirname, 'stats', 'stats-0', { assets: true, assetsSort: '\'field\'', cached: true, @@ -30,5 +30,5 @@ defineTest(__dirname, 'stats', 'stats-0', {stats: { usedExports: false, version: true, warnings: true -}}); -defineTest(__dirname, 'stats', 'stats-0', {stats: '\'errors-only\''}); +}); +defineTest(__dirname, 'stats', 'stats-0', '\'errors-only\''); diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 845678c159d..8631c308c28 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -8,15 +8,15 @@ const createSingularProperty = require('../../../transformations/utils').createS * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { - if(webpackProperties['target'] && webpackProperties['target'].length) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(j, p, createSingularProperty, 'target', webpackProperties)); + if(webpackProperties && webpackProperties.length) { + return ast.find(j.ObjectExpression) + .filter(p => isAssignment(j, p, createSingularProperty, 'target', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/target/target.test.js b/lib/creator/transformations/target/target.test.js index a91ea010dda..e42a7347a91 100644 --- a/lib/creator/transformations/target/target.test.js +++ b/lib/creator/transformations/target/target.test.js @@ -1,4 +1,4 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'target', 'target-0', {target : '\'async-node\''}); -defineTest(__dirname, 'target', 'target-1', {target : 'node'}); +defineTest(__dirname, 'target', 'target-0', '\'async-node\''); +defineTest(__dirname, 'target', 'target-1', 'node'); diff --git a/lib/creator/transformations/top-scope/top-scope.js b/lib/creator/transformations/top-scope/top-scope.js index 46d438a2320..49ef0ad42b9 100644 --- a/lib/creator/transformations/top-scope/top-scope.js +++ b/lib/creator/transformations/top-scope/top-scope.js @@ -6,12 +6,11 @@ * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing topscope properties +* @param { Object } webpackProperties - Object containing topscope properties * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.topScope; +module.exports = function(j, ast, webpackProperties) { function createTopScopeProperty(p) { webpackProperties.forEach( (n) => { p.value.body.splice(-1, 0, n); diff --git a/lib/creator/transformations/top-scope/top-scope.test.js b/lib/creator/transformations/top-scope/top-scope.test.js index d7692345ff9..da1398e55f9 100644 --- a/lib/creator/transformations/top-scope/top-scope.test.js +++ b/lib/creator/transformations/top-scope/top-scope.test.js @@ -1,5 +1,5 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'top-scope', 'top-scope-0', { topScope: [ +defineTest(__dirname, 'top-scope', 'top-scope-0', [ 'var test = \'me\';' -]}); +]); diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index dca2d49d1b6..b89f97aa063 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -8,14 +8,14 @@ const createSingularProperty = require('../../../transformations/utils').createS * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; - if(typeof(webpackProperties['watch']) === 'boolean') { - return ast.find(j.ObjectExpression).filter(p => isAssignment(j, p, createSingularProperty, 'watch', webpackProperties)); +module.exports = function(j, ast, webpackProperties) { + if(typeof(webpackProperties) === 'boolean') { + return ast.find(j.ObjectExpression) + .filter(p => isAssignment(j, p, createSingularProperty, 'watch', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/watch/watch.test.js b/lib/creator/transformations/watch/watch.test.js index 1b5e1e195c3..c564fcba4ec 100644 --- a/lib/creator/transformations/watch/watch.test.js +++ b/lib/creator/transformations/watch/watch.test.js @@ -1,6 +1,6 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'watch', 'watch-0', {watch : true}); -defineTest(__dirname, 'watch', 'watch-0', {watch : false}); -defineTest(__dirname, 'watch', 'watch-1', {watch : true}); -defineTest(__dirname, 'watch', 'watch-1', {watch : false}); +defineTest(__dirname, 'watch', 'watch-0', true); +defineTest(__dirname, 'watch', 'watch-0', false); +defineTest(__dirname, 'watch', 'watch-1', true); +defineTest(__dirname, 'watch', 'watch-1', false); diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index c327aea41f7..870773dd305 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -9,21 +9,20 @@ const utils = require('../../../transformations/utils'); * * @param j — jscodeshift API * @param ast - jscodeshift API -* @param { Object } yeomanConfig - Object containing transformation rules +* @param { Object } webpackProperties - Object containing transformation rules * @returns ast - jscodeshift API */ -module.exports = function(j, ast, yeomanConfig) { - const webpackProperties = yeomanConfig.webpackOptions; +module.exports = function(j, ast, webpackProperties) { function createWatchOptionsProperty(p) { utils.pushCreateProperty(j, p, 'watchOptions', j.objectExpression([])); p.value.properties.filter(n => (utils.safeTraverse(n, ['key', 'name']) === 'watchOptions') ).forEach( (prop) => { - Object.keys(webpackProperties['watchOptions']).filter( (watchOption) => { + Object.keys(webpackProperties).filter( (watchOption) => { if(watchOptionTypes.includes(watchOption)) { utils.pushCreateProperty( - j, prop, watchOption, webpackProperties.watchOptions[watchOption] + j, prop, watchOption, webpackProperties[watchOption] ); } else { throw new Error('Unknown Property', watchOption); @@ -31,7 +30,7 @@ module.exports = function(j, ast, yeomanConfig) { }); }); } - if(webpackProperties['watchOptions']) { + if(webpackProperties) { return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createWatchOptionsProperty)); } else { return ast; diff --git a/lib/creator/transformations/watch/watchOptions.test.js b/lib/creator/transformations/watch/watchOptions.test.js index c457bfbb388..33eb8811e08 100644 --- a/lib/creator/transformations/watch/watchOptions.test.js +++ b/lib/creator/transformations/watch/watchOptions.test.js @@ -1,19 +1,19 @@ const defineTest = require('../../../transformations/defineTest'); -defineTest(__dirname, 'watchOptions', 'watch-0', {watchOptions : { +defineTest(__dirname, 'watchOptions', 'watch-0', { aggregateTimeout: 300, poll: 1000, ignored: '/node_modules/' -}}); +}); -defineTest(__dirname, 'watchOptions', 'watch-1', {watchOptions : { +defineTest(__dirname, 'watchOptions', 'watch-1', { aggregateTimeout: 300, poll: 1000, ignored: '/node_modules/' -}}); +}); -defineTest(__dirname, 'watchOptions', 'watch-2', {watchOptions : { +defineTest(__dirname, 'watchOptions', 'watch-2', { aggregateTimeout: 300, poll: 1000, ignored: '/node_modules/' -}}); +}); diff --git a/lib/transformations/defineTest.js b/lib/transformations/defineTest.js index c2ef471e89d..2824337e41e 100644 --- a/lib/transformations/defineTest.js +++ b/lib/transformations/defineTest.js @@ -26,7 +26,6 @@ function runSingleTansform(dirName, transformName, testFilePrefix, initOptions) if (!testFilePrefix) { testFilePrefix = transformName; } - const fixtureDir = path.join(dirName, '__testfixtures__'); const inputPath = path.join(fixtureDir, testFilePrefix + '.input.js'); const source = fs.readFileSync(inputPath, 'utf8'); @@ -42,14 +41,8 @@ function runSingleTansform(dirName, transformName, testFilePrefix, initOptions) jscodeshift = jscodeshift.withParser(module.parser); } const ast = jscodeshift(source); - if (initOptions) { - if (initOptions.topScope) { - return transform(jscodeshift, ast, initOptions).toSource({ quote: 'single' }); - } else { - return transform(jscodeshift, ast, { - webpackOptions: initOptions - }).toSource({ quote: 'single' }); - } + if (initOptions || typeof(initOptions) === 'boolean') { + return transform(jscodeshift, ast, initOptions).toSource({ quote: 'single' }); } return transform(jscodeshift, ast, source).toSource({ quote: 'single' }); } diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index 2744d065646..b15a4a877a6 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -385,7 +385,6 @@ function pushCreateProperty(j, p, key, val) { } else { property = createIdentifierOrLiteral(j, val); } - return p.value.properties.push( createObjectWithSuppliedProperty(j, key, property) ); @@ -403,7 +402,7 @@ function pushCreateProperty(j, p, key, val) { */ function createSingularProperty(j, p, name, webpackProperties) { - return pushCreateProperty(j, p, name, webpackProperties[name]); + return pushCreateProperty(j, p, name, webpackProperties); } /* diff --git a/lib/transformations/utils.test.js b/lib/transformations/utils.test.js index b67e3d201a7..62afc9ab7f1 100644 --- a/lib/transformations/utils.test.js +++ b/lib/transformations/utils.test.js @@ -258,9 +258,7 @@ var a = { plugs: [] } describe('createSingularProperty', () => { it('should create an single property with no nested properties', () => { const ast = j('module.exports = {}'); - const myObj = { - context: 'Heyho' - }; + const myObj = 'Heyho'; const myKey = 'context'; ast.find(j.ObjectExpression) @@ -274,9 +272,7 @@ var a = { plugs: [] } describe('isAssignment', () => { it('should invoke a callback if parent type is AssignmentExpression', () => { const ast = j('module.exports = {}'); - const myObj = { - context: 'Heyho' - }; + const myObj = 'Heyho'; const myKey = 'context'; ast.find(j.ObjectExpression) From 08bb8e512d9edeeb576e3d2956d71d378bdd8401 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 23 Apr 2017 20:08:30 +0200 Subject: [PATCH 069/101] enhancements: remove createsingular Replaced by pushCreateProperty --- .../transformations/context/context.js | 4 ++-- .../transformations/devtool/devtool.js | 4 ++-- lib/creator/transformations/other/bail.js | 4 ++-- lib/creator/transformations/other/cache.js | 4 ++-- lib/creator/transformations/other/profile.js | 4 ++-- lib/creator/transformations/target/target.js | 4 ++-- lib/creator/transformations/watch/watch.js | 4 ++-- .../__snapshots__/utils.test.js.snap | 6 ------ lib/transformations/utils.js | 20 ++----------------- lib/transformations/utils.test.js | 16 +-------------- 10 files changed, 17 insertions(+), 53 deletions(-) diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index ab452c0bfa5..539e6104f84 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,5 +1,5 @@ const isAssignment = require('../../../transformations/utils').isAssignment; -const createSingularProperty = require('../../../transformations/utils').createSingularProperty; +const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; /* @@ -16,7 +16,7 @@ const createSingularProperty = require('../../../transformations/utils').createS module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, createSingularProperty, 'context', webpackProperties)); + .filter(p => isAssignment(j, p, pushCreateProperty, 'context', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index 772254aa4e6..a491ab402b6 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,5 +1,5 @@ const isAssignment = require('../../../transformations/utils').isAssignment; -const createSingularProperty = require('../../../transformations/utils').createSingularProperty; +const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; /* @@ -17,7 +17,7 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, createSingularProperty, 'devtool', webpackProperties)); + .filter(p => isAssignment(j, p, pushCreateProperty, 'devtool', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index 1950eaa1dd6..23fa5fef1f3 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,5 +1,5 @@ const isAssignment = require('../../../transformations/utils').isAssignment; -const createSingularProperty = require('../../../transformations/utils').createSingularProperty; +const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; /* @@ -17,7 +17,7 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, createSingularProperty, 'bail', webpackProperties)); + .filter(p => isAssignment(j, p, pushCreateProperty, 'bail', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index e9d88931420..08b649cdfe8 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,5 +1,5 @@ const isAssignment = require('../../../transformations/utils').isAssignment; -const createSingularProperty = require('../../../transformations/utils').createSingularProperty; +const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; /* @@ -17,7 +17,7 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, createSingularProperty, 'cache', webpackProperties)); + .filter(p => isAssignment(j, p, pushCreateProperty, 'cache', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index 30f7b55717e..f112be2e4cf 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,5 +1,5 @@ const isAssignment = require('../../../transformations/utils').isAssignment; -const createSingularProperty = require('../../../transformations/utils').createSingularProperty; +const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; /* @@ -16,7 +16,7 @@ const createSingularProperty = require('../../../transformations/utils').createS module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, createSingularProperty, 'profile', webpackProperties)); + .filter(p => isAssignment(j, p, pushCreateProperty, 'profile', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index 8631c308c28..f438f67ae95 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,5 +1,5 @@ const isAssignment = require('../../../transformations/utils').isAssignment; -const createSingularProperty = require('../../../transformations/utils').createSingularProperty; +const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; /* * @@ -16,7 +16,7 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties && webpackProperties.length) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, createSingularProperty, 'target', webpackProperties)); + .filter(p => isAssignment(j, p, pushCreateProperty, 'target', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index b89f97aa063..95960ffa315 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,5 +1,5 @@ const isAssignment = require('../../../transformations/utils').isAssignment; -const createSingularProperty = require('../../../transformations/utils').createSingularProperty; +const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; /* * @@ -15,7 +15,7 @@ const createSingularProperty = require('../../../transformations/utils').createS module.exports = function(j, ast, webpackProperties) { if(typeof(webpackProperties) === 'boolean') { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, createSingularProperty, 'watch', webpackProperties)); + .filter(p => isAssignment(j, p, pushCreateProperty, 'watch', webpackProperties)); } else { return ast; } diff --git a/lib/transformations/__snapshots__/utils.test.js.snap b/lib/transformations/__snapshots__/utils.test.js.snap index 38442c773dd..1829b0aec30 100644 --- a/lib/transformations/__snapshots__/utils.test.js.snap +++ b/lib/transformations/__snapshots__/utils.test.js.snap @@ -87,12 +87,6 @@ exports[`utils createProperty should create properties for non-literal keys 1`] }" `; -exports[`utils createSingularProperty should create an single property with no nested properties 1`] = ` -"module.exports = { - context: Heyho -}" -`; - exports[`utils getRequire should create a require statement 1`] = `"const filesys = require(\\"fs\\");"`; exports[`utils isAssignment should allow custom transform functions instead of singularProperty 1`] = ` diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index b15a4a877a6..7cf3548a4d4 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -390,33 +390,18 @@ function pushCreateProperty(j, p, key, val) { ); } -/* -* @function createSingularProperty -* -* Creates an assignment with given properties from yeoman -* @param j — jscodeshift API -* @param { Node } p - Node to push against -* @param { String } name - key used as identifier -* @param { String } webpackProperties - property value to add with key -* @returns - { Node } - Returns node the pushed property -*/ - -function createSingularProperty(j, p, name, webpackProperties) { - return pushCreateProperty(j, p, name, webpackProperties); -} - /* * @function isAssignment * * Checks if we are at the correct node and later invokes a callback * for the transforms to either use their own transform function or -* use createSingularProperty if the transform doesn't expect any properties +* use pushCreateProperty if the transform doesn't expect any properties * @param j — jscodeshift API * @param { Node } p - Node to push against * @param { Function } cb - callback to be invoked * @param { String } identifier - key to use as property * @param { Object } property - WebpackOptions that later will be converted via -* createSingularProperty via WebpackOptions[identifier] +* pushCreateProperty via WebpackOptions[identifier] * @returns - { Function } cb - Returns the callback and pushes a new node */ @@ -449,6 +434,5 @@ module.exports = { createObjectWithSuppliedProperty, createExternalRegExp, pushCreateProperty, - createSingularProperty, isAssignment }; diff --git a/lib/transformations/utils.test.js b/lib/transformations/utils.test.js index 62afc9ab7f1..0b2d95a048a 100644 --- a/lib/transformations/utils.test.js +++ b/lib/transformations/utils.test.js @@ -255,20 +255,6 @@ var a = { plugs: [] } expect(ast.toSource()).toMatchSnapshot(); }); }); - describe('createSingularProperty', () => { - it('should create an single property with no nested properties', () => { - const ast = j('module.exports = {}'); - const myObj = 'Heyho'; - const myKey = 'context'; - - ast.find(j.ObjectExpression) - .filter(n => n.parent.value.type === 'AssignmentExpression') - .forEach(node => { - utils.createSingularProperty(j, node, myKey, myObj); - }); - expect(ast.toSource()).toMatchSnapshot(); - }); - }); describe('isAssignment', () => { it('should invoke a callback if parent type is AssignmentExpression', () => { const ast = j('module.exports = {}'); @@ -276,7 +262,7 @@ var a = { plugs: [] } const myKey = 'context'; ast.find(j.ObjectExpression) - .filter(n => utils.isAssignment(j, n, utils.createSingularProperty, myKey, myObj)); + .filter(n => utils.isAssignment(j, n, utils.pushCreateProperty, myKey, myObj)); expect(ast.toSource()).toMatchSnapshot(); }); it('should allow custom transform functions instead of singularProperty', () => { From b458b9e7d999b7c83a6e235c7384928c22992753 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 23 Apr 2017 22:29:52 +0200 Subject: [PATCH 070/101] enhancements: use more utility and remove boilerplate code --- .../transformations/context/context.js | 5 +-- .../transformations/devtool/devtool.js | 5 +-- lib/creator/transformations/entry/entry.js | 3 +- lib/creator/transformations/node/node.js | 15 +------- lib/creator/transformations/other/amd.js | 14 +------ lib/creator/transformations/other/bail.js | 5 +-- lib/creator/transformations/other/cache.js | 5 +-- lib/creator/transformations/other/profile.js | 5 +-- .../transformations/output/output-types.js | 24 ------------ lib/creator/transformations/output/output.js | 23 +----------- .../performance/performance-types.js | 6 --- .../performance/performance.js | 18 +-------- .../transformations/plugins/plugins.js | 3 +- .../transformations/resolve/resolve.js | 3 +- .../transformations/stats/stats-types.js | 31 ---------------- lib/creator/transformations/stats/stats.js | 36 ++---------------- lib/creator/transformations/target/target.js | 5 +-- lib/creator/transformations/watch/watch.js | 5 +-- .../watch/watchOptions-types.js | 5 --- .../transformations/watch/watchOptions.js | 19 ++-------- lib/transformations/utils.js | 37 ++++++++++++++++++- 21 files changed, 68 insertions(+), 204 deletions(-) delete mode 100644 lib/creator/transformations/output/output-types.js delete mode 100644 lib/creator/transformations/performance/performance-types.js delete mode 100644 lib/creator/transformations/stats/stats-types.js delete mode 100644 lib/creator/transformations/watch/watchOptions-types.js diff --git a/lib/creator/transformations/context/context.js b/lib/creator/transformations/context/context.js index 539e6104f84..98fb0710b99 100644 --- a/lib/creator/transformations/context/context.js +++ b/lib/creator/transformations/context/context.js @@ -1,5 +1,4 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; -const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; +const utils = require('../../../transformations/utils'); /* @@ -16,7 +15,7 @@ const pushCreateProperty = require('../../../transformations/utils').pushCreateP module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, pushCreateProperty, 'context', webpackProperties)); + .filter(p => utils.isAssignment(j, p, utils.pushCreateProperty, 'context', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/devtool/devtool.js b/lib/creator/transformations/devtool/devtool.js index a491ab402b6..ac3930ad366 100644 --- a/lib/creator/transformations/devtool/devtool.js +++ b/lib/creator/transformations/devtool/devtool.js @@ -1,5 +1,4 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; -const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; +const utils = require('../../../transformations/utils'); /* @@ -17,7 +16,7 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, pushCreateProperty, 'devtool', webpackProperties)); + .filter(p => utils.isAssignment(j, p, utils.pushCreateProperty, 'devtool', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index c602856f1a0..a3a69a40529 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -1,4 +1,3 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); @@ -45,7 +44,7 @@ module.exports = function(j, ast, webpackProperties) { } if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(null, p, createEntryProperty)); + .filter(p => utils.isAssignment(null, p, createEntryProperty)); } else { return ast; } diff --git a/lib/creator/transformations/node/node.js b/lib/creator/transformations/node/node.js index bc92fe0941e..26a9a13ffe4 100644 --- a/lib/creator/transformations/node/node.js +++ b/lib/creator/transformations/node/node.js @@ -1,4 +1,3 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); @@ -16,21 +15,11 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { function createNodeProperty(p) { utils.pushCreateProperty(j, p, 'node', j.objectExpression([])); - - let node = p.value.properties; - node.filter(n => - (utils.safeTraverse(n, ['key', 'name']) === 'node') - ).forEach( (prop) => { - Object.keys(webpackProperties).forEach( (webpackProp) => { - utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties[webpackProp] - ); - }); - }); + return utils.pushObjectKeys(j, p, webpackProperties, 'node'); } if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(null, p, createNodeProperty)); + .filter(p => utils.isAssignment(null, p, createNodeProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/amd.js b/lib/creator/transformations/other/amd.js index 167f062155b..8453e6105c1 100644 --- a/lib/creator/transformations/other/amd.js +++ b/lib/creator/transformations/other/amd.js @@ -1,4 +1,3 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); @@ -16,20 +15,11 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { function createAMDProperty(p) { utils.pushCreateProperty(j, p, 'amd', j.objectExpression([])); - let amdNode = p.value.properties; - amdNode.filter(n => - (utils.safeTraverse(n, ['key', 'name']) === 'amd') - ).forEach( (prop) => { - Object.keys(webpackProperties).forEach( (webpackProp) => { - utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties[webpackProp] - ); - }); - }); + return utils.pushObjectKeys(j, p, webpackProperties, 'amd'); } if(webpackProperties && typeof(webpackProperties) === 'object') { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(null, p, createAMDProperty)); + .filter(p => utils.isAssignment(null, p, createAMDProperty)); } else { return ast; } diff --git a/lib/creator/transformations/other/bail.js b/lib/creator/transformations/other/bail.js index 23fa5fef1f3..b61d793f30a 100644 --- a/lib/creator/transformations/other/bail.js +++ b/lib/creator/transformations/other/bail.js @@ -1,5 +1,4 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; -const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; +const utils = require('../../../transformations/utils'); /* @@ -17,7 +16,7 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, pushCreateProperty, 'bail', webpackProperties)); + .filter(p => utils.isAssignment(j, p, utils.pushCreateProperty, 'bail', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/other/cache.js b/lib/creator/transformations/other/cache.js index 08b649cdfe8..ad0ee5d5e0c 100644 --- a/lib/creator/transformations/other/cache.js +++ b/lib/creator/transformations/other/cache.js @@ -1,5 +1,4 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; -const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; +const utils = require('../../../transformations/utils'); /* @@ -17,7 +16,7 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, pushCreateProperty, 'cache', webpackProperties)); + .filter(p => utils.isAssignment(j, p, utils.pushCreateProperty, 'cache', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/other/profile.js b/lib/creator/transformations/other/profile.js index f112be2e4cf..bdb146dc9d4 100644 --- a/lib/creator/transformations/other/profile.js +++ b/lib/creator/transformations/other/profile.js @@ -1,5 +1,4 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; -const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; +const utils = require('../../../transformations/utils'); /* @@ -16,7 +15,7 @@ const pushCreateProperty = require('../../../transformations/utils').pushCreateP module.exports = function(j, ast, webpackProperties) { if(webpackProperties) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, pushCreateProperty, 'profile', webpackProperties)); + .filter(p => utils.isAssignment(j, p, utils.pushCreateProperty, 'profile', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/output/output-types.js b/lib/creator/transformations/output/output-types.js deleted file mode 100644 index 986d9229386..00000000000 --- a/lib/creator/transformations/output/output-types.js +++ /dev/null @@ -1,24 +0,0 @@ -module.exports = [ - 'chunkFilename', - 'crossOriginLoading', - 'devtoolFallbackModuleFilenameTemplate', - 'devtoolLineToLine', - 'hashFunction', - 'hashDigest', - 'hashDigestLength', - 'hashSalt', - 'filename', - 'hotUpdateChunkFilename', - 'hotUpdateFunction', - 'hotUpdateMainFilename', - 'jsonpFunction', - 'libary', - 'libaryTarget', - 'path', - 'pathinfo', - 'publicPath', - 'sourceMapFilename', - 'sourcePrefix', - 'strictModuleExceptionHandling', - 'umdNamedDefine' -]; diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index 3113f4c5b25..b79e5e95d25 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -1,5 +1,3 @@ -const webpackOutputTypes = require('./output-types'); -const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); @@ -17,27 +15,10 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { function createOutputProperties(p) { utils.pushCreateProperty(j, p, 'output', j.objectExpression([])); - let outputNode = p.value.properties; - outputNode.filter( n => - (utils.safeTraverse(n, ['key', 'name']) === 'output') - ).forEach( (prop) => { - Object.keys(webpackProperties).forEach( (webpackProp) => { - if(webpackOutputTypes.includes(webpackProp)) { - if(webpackProperties[webpackProp].__paths) { - let regExpProp = utils.createExternalRegExp(j, webpackProperties[webpackProp]); - utils.pushCreateProperty(j, prop, webpackProp, regExpProp); - } - else { - utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties[webpackProp] - ); - } - } - }); - }); + return utils.pushObjectKeys(j, p, webpackProperties, 'output'); } if(webpackProperties) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createOutputProperties)); + return ast.find(j.ObjectExpression).filter(p => utils.isAssignment(null, p, createOutputProperties)); } else { return ast; } diff --git a/lib/creator/transformations/performance/performance-types.js b/lib/creator/transformations/performance/performance-types.js deleted file mode 100644 index cbaf31dd699..00000000000 --- a/lib/creator/transformations/performance/performance-types.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = [ - 'hints', - 'maxEntrypointSize', - 'maxAssetSize', - 'assetFilter' -]; diff --git a/lib/creator/transformations/performance/performance.js b/lib/creator/transformations/performance/performance.js index 9b8bc241e32..7450f12df62 100644 --- a/lib/creator/transformations/performance/performance.js +++ b/lib/creator/transformations/performance/performance.js @@ -1,5 +1,3 @@ -const performanceTypes = require('./performance-types'); -const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); @@ -17,24 +15,12 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { function createPerformanceProperty(p) { - utils.pushCreateProperty(j, p, 'performance', j.objectExpression([])); - let performanceNode = p.value.properties; - performanceNode.filter(n => - (utils.safeTraverse(n, ['key', 'name']) === 'performance') - ).forEach( (prop) => { - Object.keys(webpackProperties).forEach( (webpackProp) => { - if(performanceTypes.includes(webpackProp)) { - utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties[webpackProp] - ); - } - }); - }); + return utils.pushObjectKeys(j, p, webpackProperties, 'performance'); } if(webpackProperties && typeof(webpackProperties) === 'object') { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(null, p, createPerformanceProperty)); + .filter(p => utils.isAssignment(null, p, createPerformanceProperty)); } else { return ast; } diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index c937487ae8a..35b294a2f03 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -1,4 +1,3 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); /* @@ -18,7 +17,7 @@ module.exports = function(j, ast, webpackProperties) { return p.value.properties.push(pluginArray); } if(webpackProperties && Array.isArray(webpackProperties)) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createPluginsProperty)); + return ast.find(j.ObjectExpression).filter(p => utils.isAssignment(null, p, createPluginsProperty)); } else { return ast; } diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index d5f4a39b9a7..0b246da4e3d 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -1,5 +1,4 @@ const resolveTypes = require('./resolve-types'); -const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); /* @@ -70,7 +69,7 @@ module.exports = function(j, ast, webpackProperties) { }); } if(webpackProperties) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createResolveProperties)); + return ast.find(j.ObjectExpression).filter(p => utils.isAssignment(null, p, createResolveProperties)); } else { return ast; diff --git a/lib/creator/transformations/stats/stats-types.js b/lib/creator/transformations/stats/stats-types.js deleted file mode 100644 index 6a6dfd136a6..00000000000 --- a/lib/creator/transformations/stats/stats-types.js +++ /dev/null @@ -1,31 +0,0 @@ -module.exports = [ - 'assets', - 'assetsSort', - 'cached', - 'cachedAssets', - 'children', - 'chunks', - 'chunkModules', - 'chunkOrigins', - 'chunksSort', - 'context', - 'colors', - 'depth', - 'entrypoints', - 'errors', - 'errorDetails', - 'exclude', - 'hash', - 'maxModules', - 'modules', - 'modulesSort', - 'performance', - 'providedExports', - 'publicPath', - 'reasons', - 'source', - 'timings', - 'usedExports', - 'version', - 'warnings' -]; diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index dacd3f0f6ca..3d104f4deee 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -1,5 +1,3 @@ -const statsTypes = require('./stats-types'); -const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); /* @@ -16,41 +14,15 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { function createStatsProperty(p) { utils.pushCreateProperty(j, p, 'stats', j.objectExpression([])); - let statsNode = p.value.properties; - statsNode.filter(n => - (utils.safeTraverse(n, ['key', 'name']) === 'stats') - ).forEach( (prop) => { - Object.keys(webpackProperties).forEach( (webpackProp) => { - if(statsTypes.includes(webpackProp)) { - if(Array.isArray(webpackProperties[webpackProp])) { - const statsArray = utils.createArrayWithChildren( - j, webpackProp, webpackProperties[webpackProp], true - ); - prop.value.properties.push(statsArray); - } - else { - utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties[webpackProp] - ); - } - } else { - throw new Error('Unknown Property', webpackProp); - } - }); - }); + return utils.pushObjectKeys(j, p, webpackProperties, 'stats'); } if(webpackProperties && typeof(webpackProperties) === 'object') { - return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createStatsProperty)); + return ast.find(j.ObjectExpression).filter(p => utils.isAssignment(null, p, createStatsProperty)); } // FIXME -> HOC AssignmentExpression else if(webpackProperties && webpackProperties.length) { - return ast.find(j.ObjectExpression).filter(p => { - if(p.parent.value.type === 'AssignmentExpression') { - return p.value.properties.push( - j.property('init', j.identifier('stats'), j.identifier(webpackProperties)) - ); - } - }); + return ast.find(j.ObjectExpression) + .filter(p => utils.isAssignment(j, p, utils.pushCreateProperty, 'stats', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/target/target.js b/lib/creator/transformations/target/target.js index f438f67ae95..01501315d1d 100644 --- a/lib/creator/transformations/target/target.js +++ b/lib/creator/transformations/target/target.js @@ -1,5 +1,4 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; -const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; +const utils = require('../../../transformations/utils'); /* * @@ -16,7 +15,7 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties && webpackProperties.length) { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, pushCreateProperty, 'target', webpackProperties)); + .filter(p => utils.isAssignment(j, p, utils.pushCreateProperty, 'target', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/watch/watch.js b/lib/creator/transformations/watch/watch.js index 95960ffa315..650ddd22805 100644 --- a/lib/creator/transformations/watch/watch.js +++ b/lib/creator/transformations/watch/watch.js @@ -1,5 +1,4 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; -const pushCreateProperty = require('../../../transformations/utils').pushCreateProperty; +const utils = require('../../../transformations/utils'); /* * @@ -15,7 +14,7 @@ const pushCreateProperty = require('../../../transformations/utils').pushCreateP module.exports = function(j, ast, webpackProperties) { if(typeof(webpackProperties) === 'boolean') { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(j, p, pushCreateProperty, 'watch', webpackProperties)); + .filter(p => utils.isAssignment(j, p, utils.pushCreateProperty, 'watch', webpackProperties)); } else { return ast; } diff --git a/lib/creator/transformations/watch/watchOptions-types.js b/lib/creator/transformations/watch/watchOptions-types.js deleted file mode 100644 index 4a352059ebb..00000000000 --- a/lib/creator/transformations/watch/watchOptions-types.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = [ - 'aggregateTimeout', - 'ignored', - 'poll' -]; diff --git a/lib/creator/transformations/watch/watchOptions.js b/lib/creator/transformations/watch/watchOptions.js index 870773dd305..b08c8218a5c 100644 --- a/lib/creator/transformations/watch/watchOptions.js +++ b/lib/creator/transformations/watch/watchOptions.js @@ -1,5 +1,3 @@ -const watchOptionTypes = require('./watchOptions-types'); -const isAssignment = require('../../../transformations/utils').isAssignment; const utils = require('../../../transformations/utils'); /* @@ -16,22 +14,11 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { function createWatchOptionsProperty(p) { utils.pushCreateProperty(j, p, 'watchOptions', j.objectExpression([])); - p.value.properties.filter(n => - (utils.safeTraverse(n, ['key', 'name']) === 'watchOptions') - ).forEach( (prop) => { - Object.keys(webpackProperties).filter( (watchOption) => { - if(watchOptionTypes.includes(watchOption)) { - utils.pushCreateProperty( - j, prop, watchOption, webpackProperties[watchOption] - ); - } else { - throw new Error('Unknown Property', watchOption); - } - }); - }); + return utils.pushObjectKeys(j, p, webpackProperties, 'watchOptions'); } if(webpackProperties) { - return ast.find(j.ObjectExpression).filter(p => isAssignment(null, p, createWatchOptionsProperty)); + return ast.find(j.ObjectExpression) + .filter(p => utils.isAssignment(null, p, createWatchOptionsProperty)); } else { return ast; } diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index 7cf3548a4d4..d5f5b96806e 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -124,7 +124,7 @@ function createLiteral(j, val) { function createIdentifierOrLiteral(j, val) { let literalVal = val; // We'll need String to native type conversions - if (typeof val === 'string') { + if (typeof val === 'string' || val.__paths) { // 'true' => true if (val === 'true') { literalVal = true; @@ -140,6 +140,10 @@ function createIdentifierOrLiteral(j, val) { literalVal = Number(val); return j.literal(literalVal); } + + if(val.__paths) { + return createExternalRegExp(j, val); + } // Use identifier instead else { return j.identifier(literalVal); @@ -390,6 +394,36 @@ function pushCreateProperty(j, p, key, val) { ); } +/* +* @function pushObjectKeys +* +* @param j — jscodeshift API +* @param { Node } p - path to push +* @param { Object } webpackProperties - The object to loop over +* @param { String } name - Key that will be the identifier we find and add values to +* @returns - { Node/Function } Returns a function that will push a node if +*subProperty is an array, else it will invoke a function that will push a single node +*/ + +function pushObjectKeys(j, p, webpackProperties, name) { + p.value.properties.filter(n => + (safeTraverse(n, ['key', 'name']) === name) + ).forEach( (prop) => { + Object.keys(webpackProperties).forEach( (webpackProp) => { + if(Array.isArray(webpackProperties[webpackProp])) { + const propArray = createArrayWithChildren( + j, webpackProp, webpackProperties[webpackProp], true + ); + return prop.value.properties.push(propArray); + } else { + return pushCreateProperty( + j, prop, webpackProp, webpackProperties[webpackProp] + ); + } + }); + }); +} + /* * @function isAssignment * @@ -434,5 +468,6 @@ module.exports = { createObjectWithSuppliedProperty, createExternalRegExp, pushCreateProperty, + pushObjectKeys, isAssignment }; From fda1003fe4e879f678b78fde46c394c65feb60e6 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 23 Apr 2017 23:16:59 +0200 Subject: [PATCH 071/101] chore: remove fixme flag --- lib/creator/transformations/stats/stats.js | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index 3d104f4deee..24b0d682f19 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -19,7 +19,6 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties && typeof(webpackProperties) === 'object') { return ast.find(j.ObjectExpression).filter(p => utils.isAssignment(null, p, createStatsProperty)); } - // FIXME -> HOC AssignmentExpression else if(webpackProperties && webpackProperties.length) { return ast.find(j.ObjectExpression) .filter(p => utils.isAssignment(j, p, utils.pushCreateProperty, 'stats', webpackProperties)); From f2aabaa35371ead3eb0c7d62f168975e353847ea Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 23 Apr 2017 23:21:01 +0200 Subject: [PATCH 072/101] chore: prettify ast.find --- lib/creator/transformations/other/merge.js | 3 ++- lib/creator/transformations/output/output.js | 3 ++- lib/creator/transformations/plugins/plugins.js | 3 ++- lib/creator/transformations/resolve/resolve.js | 3 ++- lib/creator/transformations/stats/stats.js | 3 ++- 5 files changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/creator/transformations/other/merge.js b/lib/creator/transformations/other/merge.js index 6dad50f1f4a..dfab1a50b8d 100644 --- a/lib/creator/transformations/other/merge.js +++ b/lib/creator/transformations/other/merge.js @@ -39,7 +39,8 @@ module.exports = function(j, ast, webpackProperties) { p.value.body[bodyLength - 1] = newVal; } if(webpackProperties) { - return ast.find(j.Program).filter(p => isAssignment(null, p, createMergeProperty)); + return ast.find(j.Program) + .filter(p => isAssignment(null, p, createMergeProperty)); } else { return ast; } diff --git a/lib/creator/transformations/output/output.js b/lib/creator/transformations/output/output.js index b79e5e95d25..ea69aaab02a 100644 --- a/lib/creator/transformations/output/output.js +++ b/lib/creator/transformations/output/output.js @@ -18,7 +18,8 @@ module.exports = function(j, ast, webpackProperties) { return utils.pushObjectKeys(j, p, webpackProperties, 'output'); } if(webpackProperties) { - return ast.find(j.ObjectExpression).filter(p => utils.isAssignment(null, p, createOutputProperties)); + return ast.find(j.ObjectExpression) + .filter(p => utils.isAssignment(null, p, createOutputProperties)); } else { return ast; } diff --git a/lib/creator/transformations/plugins/plugins.js b/lib/creator/transformations/plugins/plugins.js index 35b294a2f03..33167582f29 100644 --- a/lib/creator/transformations/plugins/plugins.js +++ b/lib/creator/transformations/plugins/plugins.js @@ -17,7 +17,8 @@ module.exports = function(j, ast, webpackProperties) { return p.value.properties.push(pluginArray); } if(webpackProperties && Array.isArray(webpackProperties)) { - return ast.find(j.ObjectExpression).filter(p => utils.isAssignment(null, p, createPluginsProperty)); + return ast.find(j.ObjectExpression) + .filter(p => utils.isAssignment(null, p, createPluginsProperty)); } else { return ast; } diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index 0b246da4e3d..f36a78c3070 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -69,7 +69,8 @@ module.exports = function(j, ast, webpackProperties) { }); } if(webpackProperties) { - return ast.find(j.ObjectExpression).filter(p => utils.isAssignment(null, p, createResolveProperties)); + return ast.find(j.ObjectExpression) + .filter(p => utils.isAssignment(null, p, createResolveProperties)); } else { return ast; diff --git a/lib/creator/transformations/stats/stats.js b/lib/creator/transformations/stats/stats.js index 24b0d682f19..46a0e0ad5e3 100644 --- a/lib/creator/transformations/stats/stats.js +++ b/lib/creator/transformations/stats/stats.js @@ -17,7 +17,8 @@ module.exports = function(j, ast, webpackProperties) { return utils.pushObjectKeys(j, p, webpackProperties, 'stats'); } if(webpackProperties && typeof(webpackProperties) === 'object') { - return ast.find(j.ObjectExpression).filter(p => utils.isAssignment(null, p, createStatsProperty)); + return ast.find(j.ObjectExpression) + .filter(p => utils.isAssignment(null, p, createStatsProperty)); } else if(webpackProperties && webpackProperties.length) { return ast.find(j.ObjectExpression) From ee8714109c41dcf2e68976d637f85218ee51da42 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 24 Apr 2017 17:13:01 +0200 Subject: [PATCH 073/101] enhancements: use objKey util for entry and externals --- lib/creator/transformations/entry/entry.js | 33 ++++------ .../transformations/externals/externals.js | 65 ++----------------- lib/transformations/utils.js | 23 ++++++- 3 files changed, 37 insertions(+), 84 deletions(-) diff --git a/lib/creator/transformations/entry/entry.js b/lib/creator/transformations/entry/entry.js index a3a69a40529..5f142907561 100644 --- a/lib/creator/transformations/entry/entry.js +++ b/lib/creator/transformations/entry/entry.js @@ -15,32 +15,21 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { - function addEntryPoints(entries) { + function createEntryProperty(p) { - if(Array.isArray(entries)) { - return j.arrayExpression(entries.map(entry => utils.createIdentifierOrLiteral(j, entry))); - } else if (typeof entries === 'string') { - return utils.createIdentifierOrLiteral(j, entries); + if(typeof(webpackProperties) === 'string') { + return utils.pushCreateProperty(j, p, 'entry', webpackProperties); } - const entryKeys = Object.keys(entries); - if (entryKeys && entryKeys.length) { - return j.objectExpression( - entryKeys.map(entryKey => { - return j.property( 'init', - utils.createIdentifierOrLiteral(j, entryKey), - utils.createIdentifierOrLiteral(j, entries[entryKey]) - ); - }) + if(Array.isArray(webpackProperties)) { + const externalArray = utils.createArrayWithChildren( + j, 'entry', webpackProperties, true ); + return p.value.properties.push(externalArray); + } + else { + utils.pushCreateProperty(j, p, 'entry', j.objectExpression([])); + return utils.pushObjectKeys(j, p, webpackProperties, 'entry'); } - - } - function createEntryProperty(p) { - let entryNode = p.value.properties; - entryNode.push( - j.property( 'init', - utils.createIdentifierOrLiteral(j, 'entry'), - addEntryPoints(webpackProperties))); } if(webpackProperties) { return ast.find(j.ObjectExpression) diff --git a/lib/creator/transformations/externals/externals.js b/lib/creator/transformations/externals/externals.js index 3059b838a33..9f20dc2d801 100644 --- a/lib/creator/transformations/externals/externals.js +++ b/lib/creator/transformations/externals/externals.js @@ -17,70 +17,15 @@ module.exports = function(j, ast, webpackProperties) { if(webpackProperties instanceof RegExp || typeof(webpackProperties) === 'string') { return utils.pushCreateProperty(j, p, 'externals', webpackProperties); } - else if(Array.isArray(webpackProperties)) { - const externalArray = utils.createEmptyArrayProperty(j, 'externals'); - webpackProperties.forEach( (n) => { - // [{myprop: 'hello'}] - let objectOfArray = j.objectExpression([]); - if(typeof(n) !== 'string') { - for(let key in n) { - objectOfArray.properties.push( - utils.createObjectWithSuppliedProperty( - j, key, utils.createIdentifierOrLiteral(j, n[key])) - ); - } - externalArray.value.elements.push(objectOfArray); - } else { - // [val] - return externalArray.value.elements.push(utils.createIdentifierOrLiteral(j, n)); - } - }); + if(Array.isArray(webpackProperties)) { + const externalArray = utils.createArrayWithChildren( + j, 'externals', webpackProperties, true + ); return p.value.properties.push(externalArray); } else { utils.pushCreateProperty(j, p, 'externals', j.objectExpression([])); - let externalsProp = p.value.properties; - externalsProp.filter(n => - (utils.safeTraverse(n, ['key', 'name']) === 'externals') - ).forEach( (prop) => { - Object.keys(webpackProperties).forEach( (webpackProp) => { - if(Array.isArray(webpackProperties[webpackProp])) { - // if we got a type, we make it an array - const externalArray = utils.createArrayWithChildren( - j, webpackProp, webpackProperties[webpackProp], true - ); - prop.value.properties.push(externalArray); - } - else if(typeof(webpackProperties[webpackProp]) === 'string') { - utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties[webpackProp] - ); - } - else { - utils.pushCreateProperty( - j, prop, webpackProp, j.objectExpression([]) - ); - prop.value.properties - .filter(n => - (utils.safeTraverse(n, ['key', 'name']) === webpackProp) - ) - .forEach( (externalProp) => { - Object.keys(webpackProperties[webpackProp]).forEach( (subProps) => { - if(Array.isArray(webpackProperties[webpackProp][subProps])) { - const subExternalArray = utils.createArrayWithChildren( - j, subProps, webpackProperties[webpackProp][subProps], true - ); - externalProp.value.properties.push(subExternalArray); - } else { - utils.pushCreateProperty( - j, externalProp, subProps, webpackProperties[webpackProp][subProps] - ); - } - }); - }); - } - }); - }); + return utils.pushObjectKeys(j, p, webpackProperties, 'externals'); } } if(webpackProperties) { diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index d5f5b96806e..be281c81f04 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -334,7 +334,18 @@ function createArrayWithChildren(j, key, subProps, shouldDropKeys) { let arr = createEmptyArrayProperty(j, key); if(shouldDropKeys) { subProps.forEach( (subProperty) => { - arr.value.elements.push(createIdentifierOrLiteral(j, subProperty)); + let objectOfArray = j.objectExpression([]); + if(typeof(subProperty) !== 'string') { + for(let keyVal in subProperty) { + objectOfArray.properties.push( + createObjectWithSuppliedProperty( + j, keyVal, createIdentifierOrLiteral(j, subProperty[keyVal])) + ); + } + arr.value.elements.push(objectOfArray); + } else { + return arr.value.elements.push(createIdentifierOrLiteral(j, subProperty)); + } }); } else { Object.keys(subProps[key]).forEach( (subProperty) => { @@ -415,10 +426,18 @@ function pushObjectKeys(j, p, webpackProperties, name) { j, webpackProp, webpackProperties[webpackProp], true ); return prop.value.properties.push(propArray); - } else { + } + else if(typeof(webpackProperties[webpackProp]) !== 'object' || webpackProperties[webpackProp].__paths) { return pushCreateProperty( j, prop, webpackProp, webpackProperties[webpackProp] ); + } else { + pushCreateProperty( + j, prop, webpackProp, j.objectExpression([]) + ); + return pushObjectKeys( + j, prop, webpackProperties[webpackProp], webpackProp + ); } }); }); From 84b81276db38d791de73d6a394bef10b9c33d5f4 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 24 Apr 2017 17:26:26 +0200 Subject: [PATCH 074/101] enhancements: use utility on resolve --- .../transformations/resolve/resolve-types.js | 15 ------ .../transformations/resolve/resolve.js | 54 +------------------ 2 files changed, 1 insertion(+), 68 deletions(-) delete mode 100644 lib/creator/transformations/resolve/resolve-types.js diff --git a/lib/creator/transformations/resolve/resolve-types.js b/lib/creator/transformations/resolve/resolve-types.js deleted file mode 100644 index 0971aa1d858..00000000000 --- a/lib/creator/transformations/resolve/resolve-types.js +++ /dev/null @@ -1,15 +0,0 @@ -module.exports = [ - 'alias', - 'aliasFields', - 'descriptionFiles', - 'enforceExtension', - 'enforceModuleExtension', - 'extensions', - 'mainFields', - 'mainFiles', - 'modules', - 'unsafeCache', - 'plugins', - 'symlinks', - 'cachePredicate' -]; diff --git a/lib/creator/transformations/resolve/resolve.js b/lib/creator/transformations/resolve/resolve.js index f36a78c3070..66d572edb84 100644 --- a/lib/creator/transformations/resolve/resolve.js +++ b/lib/creator/transformations/resolve/resolve.js @@ -1,4 +1,3 @@ -const resolveTypes = require('./resolve-types'); const utils = require('../../../transformations/utils'); /* @@ -15,58 +14,7 @@ const utils = require('../../../transformations/utils'); module.exports = function(j, ast, webpackProperties) { function createResolveProperties(p) { utils.pushCreateProperty(j, p, 'resolve', j.objectExpression([])); - let resolveNode = p.value.properties; - resolveNode.filter(n => n.key.name === 'resolve').forEach( (prop) => { - Object.keys(webpackProperties).forEach( (webpackProp) => { - if(resolveTypes.includes(webpackProp) || webpackProp === 'resolveLoader') { - if(Array.isArray(webpackProperties[webpackProp])) { - // if we got a type, we make it an array - const resolveArray = utils.createArrayWithChildren( - j, webpackProp, webpackProperties[webpackProp], true - ); - prop.value.properties.push(resolveArray); - } - else if(typeof(webpackProperties[webpackProp]) === 'boolean') { - utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties[webpackProp] - ); - } - else { - utils.pushCreateProperty(j, prop, webpackProp, j.objectExpression([])); - prop.value.properties.forEach( (resolveProp) => { - if(resolveProp.key.name === webpackProp) { - if(resolveProp.key.name === 'cachePredicate') { - let cachePredicateVal = - (typeof webpackProperties[webpackProp] === 'string') ? - j.identifier(webpackProperties[webpackProp]) : - j.literal(webpackProperties[webpackProp]); - resolveProp.value = cachePredicateVal; - } - Object.keys(webpackProperties[webpackProp]).forEach( (aliasProps) => { - if(Array.isArray(webpackProperties[webpackProp][aliasProps])) { - const resolveLoaderArray = utils.createArrayWithChildren( - j, aliasProps, webpackProperties[webpackProp][aliasProps], true - ); - resolveProp.value.properties.push(resolveLoaderArray); - - } else if(webpackProperties[webpackProp][aliasProps].length > 1) { - if(aliasProps.indexOf('inject') >= 0) { - resolveProp.value.properties.push(j.identifier( - webpackProperties[webpackProp][aliasProps] - )); - } else { - utils.pushCreateProperty( - j, resolveProp, aliasProps, webpackProperties[webpackProp][aliasProps] - ); - } - } - }); - } - }); - } - } - }); - }); + return utils.pushObjectKeys(j, p, webpackProperties, 'resolve'); } if(webpackProperties) { return ast.find(j.ObjectExpression) From 74b821a53615a0f04a0235540c7a3e55026be009 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Wed, 26 Apr 2017 17:27:59 +0200 Subject: [PATCH 075/101] enhancements: fix merge & utilize module folder --- .../entry/__snapshots__/entry.test.js.snap | 15 ++- .../transformations/entry/entry.test.js | 6 ++ .../module/__snapshots__/module.test.js.snap | 58 ++++++++++- .../transformations/module/module-types.js | 17 ---- lib/creator/transformations/module/module.js | 98 ++----------------- .../transformations/module/module.test.js | 49 +++++++++- lib/creator/transformations/module/utils.js | 90 ----------------- .../other/__snapshots__/other.test.js.snap | 10 ++ lib/creator/transformations/other/merge.js | 5 +- .../transformations/other/other.test.js | 1 + .../__snapshots__/resolve.test.js.snap | 2 + .../transformations/resolve/resolve.test.js | 4 +- .../__snapshots__/utils.test.js.snap | 20 ++++ lib/transformations/utils.js | 52 ++++++++-- lib/transformations/utils.test.js | 32 ++++++ 15 files changed, 244 insertions(+), 215 deletions(-) delete mode 100644 lib/creator/transformations/module/module-types.js delete mode 100644 lib/creator/transformations/module/utils.js diff --git a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap index 62fe7f7ccf6..1fb3d3acd85 100644 --- a/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap +++ b/lib/creator/transformations/entry/__snapshots__/entry.test.js.snap @@ -26,19 +26,30 @@ exports[`entry transforms correctly using "entry-0" data 3`] = ` exports[`entry transforms correctly using "entry-0" data 4`] = ` "module.exports = { - entry: () => 'index.js' + entry: { + something, + app: 'app.js', + else + } } " `; exports[`entry transforms correctly using "entry-0" data 5`] = ` "module.exports = { - entry: () => new Promise((resolve) => resolve(['./app', './router'])) + entry: () => 'index.js' } " `; exports[`entry transforms correctly using "entry-0" data 6`] = ` +"module.exports = { + entry: () => new Promise((resolve) => resolve(['./app', './router'])) +} +" +`; + +exports[`entry transforms correctly using "entry-0" data 7`] = ` "module.exports = { entry: entryStringVariable } diff --git a/lib/creator/transformations/entry/entry.test.js b/lib/creator/transformations/entry/entry.test.js index bad451e36a2..27047eb84ee 100644 --- a/lib/creator/transformations/entry/entry.test.js +++ b/lib/creator/transformations/entry/entry.test.js @@ -6,6 +6,12 @@ defineTest(__dirname, 'entry', 'entry-0', { index: '\'index.js\'', app: '\'app.js\'' }); + +defineTest(__dirname, 'entry', 'entry-0', { + inject: 'something', + app: '\'app.js\'', + inject_1: 'else' +}); defineTest(__dirname, 'entry', 'entry-0', '() => \'index.js\''); defineTest(__dirname, 'entry', 'entry-0', '() => new Promise((resolve) => resolve([\'./app\', \'./router\']))'); defineTest(__dirname, 'entry', 'entry-0', 'entryStringVariable'); diff --git a/lib/creator/transformations/module/__snapshots__/module.test.js.snap b/lib/creator/transformations/module/__snapshots__/module.test.js.snap index 553eda336d4..6824146c497 100644 --- a/lib/creator/transformations/module/__snapshots__/module.test.js.snap +++ b/lib/creator/transformations/module/__snapshots__/module.test.js.snap @@ -45,6 +45,52 @@ exports[`module transforms correctly using "module-0" data 1`] = ` " `; +exports[`module transforms correctly using "module-0" data 2`] = ` +"module.exports = { + entry: 'index.js', + output: { + filename: 'bundle.js' + }, + + module: { + rules: [{{#if_eq build 'standalone'}}, { + test: /\\\\.(js|vue)$/, + loader: 'eslint-loader', + enforce: 'pre', + include: [customObj, 'Stringy'], + options: { + formatter: 'someOption' + } + }, { + test: /\\\\.vue$/, + loader: 'vue-loader', + options: vueObject + }, { + test: /\\\\.js$/, + loader: 'babel-loader', + include: [resolve('src'), resolve('test')] + }, { + test: /\\\\.(png|jpe?g|gif|svg)(\\\\?.*)?$/, + loader: 'url-loader', + options: { + limit: 10000, + name: utils.assetsPath('img/[name].[hash:7].[ext]'), + {{#if_eq build 'standalone'}} + } + }, { + test: /\\\\.(woff2?|eot|ttf|otf)(\\\\?.*)?$/, + loader: 'url-loader', + {{#if_eq build 'standalone'}}, + options: { + limit: 10000, + name: utils.assetsPath('fonts/[name].[hash:7].[ext]') + } + }] + } +} +" +`; + exports[`module transforms correctly using "module-1" data 1`] = ` "module.exports = { entry: 'index.js', @@ -55,7 +101,17 @@ exports[`module transforms correctly using "module-1" data 1`] = ` module: { noParse: /jquery|lodash/, rules: [{ - test: /\\\\.js$/ + test: /\\\\.js$/, + parser: { + amd: false + }, + + use: ['htmllint-loader', { + loader: 'html-loader', + options: { + hello: 'world' + } + }] }] } } diff --git a/lib/creator/transformations/module/module-types.js b/lib/creator/transformations/module/module-types.js deleted file mode 100644 index f0b74008523..00000000000 --- a/lib/creator/transformations/module/module-types.js +++ /dev/null @@ -1,17 +0,0 @@ -module.exports = [ - 'enforce', - 'exclude', - 'include', - 'issuer', - 'loader', - 'loaders', - 'oneOf', - 'options', - 'query', - 'parser', - 'resource', - 'resourceQuery', - 'rules', - 'test', - 'use' -]; diff --git a/lib/creator/transformations/module/module.js b/lib/creator/transformations/module/module.js index a61e6eb3499..66c1371dccb 100644 --- a/lib/creator/transformations/module/module.js +++ b/lib/creator/transformations/module/module.js @@ -1,6 +1,3 @@ -const webpackModuleTypes = require('./module-types'); -const isAssignment = require('../../../transformations/utils').isAssignment; -const localUtils = require('./utils'); const utils = require('../../../transformations/utils'); @@ -19,97 +16,18 @@ module.exports = function(j, ast, webpackProperties) { function createModuleProperties(p) { utils.pushCreateProperty(j, p, 'module', j.objectExpression([])); - let moduleNode = p.value.properties; - moduleNode.filter(n => - (utils.safeTraverse(n, ['key', 'name']) === 'module') - ).forEach( (prop) => { - Object.keys(webpackProperties) - .forEach( (webpackProp) => { - if(['noParse', 'rules'].includes(webpackProp)) { - if(webpackProperties[webpackProp].__paths) { - // optional if user can't use regular regexp - localUtils.regExpStrategy(j, webpackProperties, webpackProp, prop); - } - else if(Array.isArray(webpackProperties[webpackProp])) { - const rulesArray = utils.createEmptyArrayProperty(j, webpackProp); - prop.value.properties.push(rulesArray); - // Keeps track of what object we're refering to when adding props - let seen = -1; - let rulesProperties = webpackProperties[webpackProp]; - - rulesProperties - .forEach( (subProps) => { - let rulesMatchProp = prop.value.properties.filter(n => - (utils.safeTraverse(n, ['key', 'name']) === webpackProp) - ); - rulesMatchProp.forEach( moduleProp => { - for(let key in subProps) { - if(key.indexOf('inject') >= 0) { - moduleProp.value.elements.push( - subProps[key] - ); - seen += 1; - } - if(webpackModuleTypes.includes(key)) { - if(key === 'test') { - moduleProp.value.elements.push( - j.objectExpression([]) - ); - seen += 1; - localUtils.createTestProperty( - j, moduleProp, seen, key, subProps - ); - } - if(key === 'enforce' || key === 'loader') { - moduleProp.value.elements[seen].properties.push( - utils.createObjectWithSuppliedProperty( - j, - key, - utils.createIdentifierOrLiteral( - j, subProps[key] - ) - ) - ); - } - if(key === 'options' || key === 'use') { - const subProperties = (key === 'use') ? - localUtils.createUseProperties(j, key, subProps) : - localUtils.createOption(j, subProps, key); - moduleProp.value.elements[seen].properties.push( - subProperties - ); - } - if(key === 'oneOf') { - // TODO - } - if(key === 'rules') { - // TODO - } - if(key === 'resource') { - // TODO - } - if(key === 'include' || key === 'exclude') { - moduleProp.value.elements[seen].properties.push( - utils.createArrayWithChildren(j, key, subProps) - ); - } - } - } - }); - }); - } else { - return utils.pushCreateProperty( - j, prop, webpackProp, webpackProperties[webpackProp] - ); - } - } - }); - }); + return utils.safeTraverse(p, ['key', 'name'] === 'module'); + } + function createRules(p) { + return utils.pushObjectKeys( + j, p, webpackProperties, 'module' + ); } if(!webpackProperties) { return ast; } else { return ast.find(j.ObjectExpression) - .filter(p => isAssignment(null, p, createModuleProperties)); + .filter(p => utils.isAssignment(null, p, createModuleProperties)) + .forEach(p => createRules(p)); } }; diff --git a/lib/creator/transformations/module/module.test.js b/lib/creator/transformations/module/module.test.js index c2838abebc0..710060d9c5e 100644 --- a/lib/creator/transformations/module/module.test.js +++ b/lib/creator/transformations/module/module.test.js @@ -41,6 +41,53 @@ defineTest(__dirname, 'module', 'module-1', { test: new RegExp(/\.js$/), parser: { amd: false - } + }, + use: [ + '\'htmllint-loader\'', + { + loader: '\'html-loader\'', + options: { + hello: '\'world\'' + } + } + ] }] }); + +defineTest(__dirname, 'module', 'module-0', { + rules: [ + '{{#if_eq build \'standalone\'}}', + { + test: new RegExp(/\.(js|vue)$/), + loader: '\'eslint-loader\'', + enforce: '\'pre\'', + include: ['customObj', '\'Stringy\''], + options: { + formatter: '\'someOption\'' + } + }, { + test: new RegExp(/\.vue$/), + loader: '\'vue-loader\'', + options: 'vueObject' + }, { + test: new RegExp(/\.js$/), + loader: '\'babel-loader\'', + include: ['resolve(\'src\')', 'resolve(\'test\')'] + }, { + test: new RegExp(/\.(png|jpe?g|gif|svg)(\?.*)?$/), + loader: '\'url-loader\'', + options: { + limit: 10000, + name: 'utils.assetsPath(\'img/[name].[hash:7].[ext]\')', + inject: '{{#if_eq build \'standalone\'}}' + } + }, { + test: new RegExp(/\.(woff2?|eot|ttf|otf)(\?.*)?$/), + loader: '\'url-loader\'', + inject: '{{#if_eq build \'standalone\'}}', + options: { + limit: '10000', + name: 'utils.assetsPath(\'fonts/[name].[hash:7].[ext]\')' + } + }] +}); diff --git a/lib/creator/transformations/module/utils.js b/lib/creator/transformations/module/utils.js deleted file mode 100644 index 39a3babaced..00000000000 --- a/lib/creator/transformations/module/utils.js +++ /dev/null @@ -1,90 +0,0 @@ -const utils = require('../../../transformations/utils'); - -// optional for the user to parse using jscodeshift for only this if a regular regexp doesnt work. -function regExpStrategy(j, webpackProperties, webpackProp, prop) { - let RegExpDec = utils.createExternalRegExp(j, webpackProperties.module[webpackProp]); - return utils.pushCreateProperty(j, prop, webpackProp, RegExpDec); -} - -// Module.rules.myRule.test -function createTestProperty(j, moduleProp, seen, key, subProps) { - moduleProp.value.elements[seen].properties.push( - utils.createObjectWithSuppliedProperty(j, key, j.literal(subProps[key])) - ); -} -// Module.rules.myRule.option -function createOption(j, subProps, key) { - let optionVal; - let optionProp; - - if(typeof(subProps[key]) === 'string') { - optionProp = utils.createIdentifierOrLiteral(j, subProps[key]); - optionVal = utils.createObjectWithSuppliedProperty(j, key, optionProp); - } else { - optionVal = utils.createObjectWithSuppliedProperty(j, key, j.objectExpression([])); - - Object.keys(subProps[key]).forEach( (optionProperty) => { - if(Array.isArray(subProps[key][optionProperty])) { - const optionArray = utils.createArrayWithChildren( - j, optionProperty, subProps[key][optionProperty], true - ); - optionVal.value.properties.push(optionArray); - } else { - utils.pushCreateProperty(j, optionVal, optionProperty, subProps[key][optionProperty]); - } - }); - } - return optionVal; -} -// Module.rules.rule.use -function createUseProperties(j, key, subProps) { - let useVal = utils.createEmptyArrayProperty(j, key); - - Object.keys(subProps[key]).forEach( (optionProperty) => { - if(typeof(subProps[key][optionProperty]) === 'string') { - useVal.value.elements.push( - utils.createIdentifierOrLiteral(j, subProps[key][optionProperty]) - ); - } else { - let loaderProperty = j.objectExpression([]); - Object.keys(subProps[key][optionProperty]).forEach( subOptionProp => { - if(typeof(subProps[key][optionProperty][subOptionProp]) === 'string') { - loaderProperty.properties.push( - utils.createObjectWithSuppliedProperty( - j, - subOptionProp, - utils.createIdentifierOrLiteral( - j, subProps[key][optionProperty][subOptionProp] - ) - ) - ); - } else { - let subSubProps = j.objectExpression([]); - Object.keys(subProps[key][optionProperty][subOptionProp]).forEach( (underlyingOption) => { - subSubProps.properties.push( - utils.createObjectWithSuppliedProperty( - j, - underlyingOption, - utils.createIdentifierOrLiteral( - j, subProps[key][optionProperty][subOptionProp][underlyingOption] - ) - ) - ); - }); - loaderProperty.properties.push( - utils.createObjectWithSuppliedProperty(j, subOptionProp, subSubProps) - ); - } - }); - useVal.value.elements.push(loaderProperty); - } - }); - return useVal; -} - -module.exports = { - regExpStrategy, - createTestProperty, - createOption, - createUseProperties -}; diff --git a/lib/creator/transformations/other/__snapshots__/other.test.js.snap b/lib/creator/transformations/other/__snapshots__/other.test.js.snap index 8b1a26010b9..5a3d06f1f94 100644 --- a/lib/creator/transformations/other/__snapshots__/other.test.js.snap +++ b/lib/creator/transformations/other/__snapshots__/other.test.js.snap @@ -51,6 +51,16 @@ exports[`cache transforms correctly using "other-0" data 2`] = ` " `; +exports[`merge transforms correctly using "other-0" data 1`] = ` +"module.exports = merge(myConfig, { + entry: 'index.js', + output: { + filename: 'bundle.js' + } +}); +" +`; + exports[`profile transforms correctly using "other-0" data 1`] = ` "module.exports = { entry: 'index.js', diff --git a/lib/creator/transformations/other/merge.js b/lib/creator/transformations/other/merge.js index dfab1a50b8d..b93d2f4bde8 100644 --- a/lib/creator/transformations/other/merge.js +++ b/lib/creator/transformations/other/merge.js @@ -1,6 +1,3 @@ -const isAssignment = require('../../../transformations/utils').isAssignment; - - /* * * Transform for merge. Finds the merge property from yeoman and creates a way @@ -40,7 +37,7 @@ module.exports = function(j, ast, webpackProperties) { } if(webpackProperties) { return ast.find(j.Program) - .filter(p => isAssignment(null, p, createMergeProperty)); + .filter(p => createMergeProperty(p)); } else { return ast; } diff --git a/lib/creator/transformations/other/other.test.js b/lib/creator/transformations/other/other.test.js index bec70af6831..ba9d0c66ac9 100644 --- a/lib/creator/transformations/other/other.test.js +++ b/lib/creator/transformations/other/other.test.js @@ -8,3 +8,4 @@ defineTest(__dirname, 'bail', 'other-0', true); defineTest(__dirname, 'cache', 'other-0', true); defineTest(__dirname, 'cache', 'other-0', 'cacheVal'); defineTest(__dirname, 'profile', 'other-0', true); +defineTest(__dirname, 'merge', 'other-0', 'myConfig'); diff --git a/lib/creator/transformations/resolve/__snapshots__/resolve.test.js.snap b/lib/creator/transformations/resolve/__snapshots__/resolve.test.js.snap index 7b31d6803d7..8e78a7cc775 100644 --- a/lib/creator/transformations/resolve/__snapshots__/resolve.test.js.snap +++ b/lib/creator/transformations/resolve/__snapshots__/resolve.test.js.snap @@ -9,7 +9,9 @@ exports[`resolve transforms correctly using "resolve-0" data 1`] = ` resolve: { alias: { + {{#if_eq build 'standalone'}}, hello: 'world', + {{/if_eq}}, world: hello }, diff --git a/lib/creator/transformations/resolve/resolve.test.js b/lib/creator/transformations/resolve/resolve.test.js index 9b6742fa13c..53218c2a4f3 100644 --- a/lib/creator/transformations/resolve/resolve.test.js +++ b/lib/creator/transformations/resolve/resolve.test.js @@ -2,8 +2,10 @@ const defineTest = require('../../../transformations/defineTest'); defineTest(__dirname, 'resolve', 'resolve-0', { alias: { + inject: '{{#if_eq build \'standalone\'}}', hello: '\'world\'', - world: 'hello' + inject_1: '{{/if_eq}}', + world: 'hello', }, aliasFields: ['\'browser\'', 'wars'], descriptionFiles: ['\'a\'', 'b'], diff --git a/lib/transformations/__snapshots__/utils.test.js.snap b/lib/transformations/__snapshots__/utils.test.js.snap index 1829b0aec30..9ebb6a83c1f 100644 --- a/lib/transformations/__snapshots__/utils.test.js.snap +++ b/lib/transformations/__snapshots__/utils.test.js.snap @@ -101,6 +101,14 @@ exports[`utils isAssignment should invoke a callback if parent type is Assignmen }" `; +exports[`utils loopThroughObjects Use recursion and add elements to an node 1`] = ` +"module.exports = { + hello: { + webpack: cli + } +}" +`; + exports[`utils pushCreateProperty should create an object or property and push the value to a node 1`] = ` "module.exports = { pushMe: { @@ -108,3 +116,15 @@ exports[`utils pushCreateProperty should create an object or property and push t } }" `; + +exports[`utils pushObjectKeys should push object to an node using Object.keys 1`] = ` +"module.exports = { + pushMe: { + hello: { + world: { + its: 'great' + } + } + } + }" +`; diff --git a/lib/transformations/utils.js b/lib/transformations/utils.js index be281c81f04..73623e70276 100644 --- a/lib/transformations/utils.js +++ b/lib/transformations/utils.js @@ -330,18 +330,14 @@ function createEmptyArrayProperty(j, key) { * @param { string } subProps - computed value of the property * @returns - { Array } arr - An array with the object properties */ + function createArrayWithChildren(j, key, subProps, shouldDropKeys) { let arr = createEmptyArrayProperty(j, key); if(shouldDropKeys) { subProps.forEach( (subProperty) => { let objectOfArray = j.objectExpression([]); if(typeof(subProperty) !== 'string') { - for(let keyVal in subProperty) { - objectOfArray.properties.push( - createObjectWithSuppliedProperty( - j, keyVal, createIdentifierOrLiteral(j, subProperty[keyVal])) - ); - } + loopThroughObjects(j, objectOfArray, subProperty); arr.value.elements.push(objectOfArray); } else { return arr.value.elements.push(createIdentifierOrLiteral(j, subProperty)); @@ -355,6 +351,39 @@ function createArrayWithChildren(j, key, subProps, shouldDropKeys) { return arr; } +/* +* @function loopThroughObjects +* +* Loops through an object and adds property to an object with no identifier +* @param j — jscodeshift API +* @param { Node } p - node to add value to +* @param { Object } obj - Object to loop through +* @returns - { Function|Node } - Either pushes the node, or reruns until +* nothing is left +*/ + +function loopThroughObjects(j, p, obj) { + Object.keys(obj).forEach( (prop) => { + if(prop.indexOf('inject') >= 0) { + return p.properties.push(createIdentifierOrLiteral(j, obj[prop])); + } + // eslint-disable-next-line no-irregular-whitespace + if(typeof(obj[prop]) !== 'object' || obj[prop] instanceof RegExp) { + p.properties.push(createObjectWithSuppliedProperty( + j, prop, createIdentifierOrLiteral(j, obj[prop]) + )); + } else if(Array.isArray(obj[prop])) { + let arrayProp = createArrayWithChildren(j, prop, obj[prop], true); + p.properties.push(arrayProp); + } else { + let objectBlock = j.objectExpression([]); + let propertyOfBlock = createObjectWithSuppliedProperty(j, prop, objectBlock); + loopThroughObjects(j, objectBlock, obj[prop]); + p.properties.push(propertyOfBlock); + } + }); +} + /* * @function createObjectWithSuppliedProperty * @@ -377,6 +406,7 @@ function createObjectWithSuppliedProperty(j, key, prop) { * @param { String } prop - property to find the value at * @returns - { Node } - A literal node with the found regexp */ + function createExternalRegExp(j, prop) { let regExpProp = prop.__paths[0].value.program.body[0].expression; return j.literal(regExpProp.value); @@ -421,13 +451,16 @@ function pushObjectKeys(j, p, webpackProperties, name) { (safeTraverse(n, ['key', 'name']) === name) ).forEach( (prop) => { Object.keys(webpackProperties).forEach( (webpackProp) => { - if(Array.isArray(webpackProperties[webpackProp])) { + if(webpackProp.indexOf('inject') >= 0) { + return prop.value.properties.push(createIdentifierOrLiteral(j, webpackProperties[webpackProp])); + } + else if(Array.isArray(webpackProperties[webpackProp])) { const propArray = createArrayWithChildren( j, webpackProp, webpackProperties[webpackProp], true ); return prop.value.properties.push(propArray); } - else if(typeof(webpackProperties[webpackProp]) !== 'object' || webpackProperties[webpackProp].__paths) { + else if(typeof(webpackProperties[webpackProp]) !== 'object' || webpackProperties[webpackProp].__paths || webpackProperties[webpackProp] instanceof RegExp) { return pushCreateProperty( j, prop, webpackProp, webpackProperties[webpackProp] ); @@ -488,5 +521,6 @@ module.exports = { createExternalRegExp, pushCreateProperty, pushObjectKeys, - isAssignment + isAssignment, + loopThroughObjects }; diff --git a/lib/transformations/utils.test.js b/lib/transformations/utils.test.js index 0b2d95a048a..c0adae775d3 100644 --- a/lib/transformations/utils.test.js +++ b/lib/transformations/utils.test.js @@ -255,6 +255,38 @@ var a = { plugs: [] } expect(ast.toSource()).toMatchSnapshot(); }); }); + describe('pushObjectKeys', () => { + it('should push object to an node using Object.keys', () => { + const ast = j(`module.exports = { + pushMe: {} + }`); + const webpackProperties = { + hello: { + world: { + its: '\'great\'' + } + } + }; + ast.find(j.ObjectExpression).forEach(node => { + utils.pushObjectKeys(j, node, webpackProperties, 'pushMe'); + }); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); + describe('loopThroughObjects', () => { + it('Use recursion and add elements to an node', () => { + const ast = j('module.exports = {}'); + const webpackProperties = { + hello: { + webpack: 'cli' + } + }; + ast.find(j.ObjectExpression).forEach(node => { + return utils.loopThroughObjects(j, node.value, webpackProperties); + }); + expect(ast.toSource()).toMatchSnapshot(); + }); + }); describe('isAssignment', () => { it('should invoke a callback if parent type is AssignmentExpression', () => { const ast = j('module.exports = {}'); From b34e93ec60eaf58e1dd49b84aa14dffd3f4b6793 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 30 Apr 2017 17:37:25 +0200 Subject: [PATCH 076/101] enhancements: use prettier node API --- lib/creator/transformations/index.js | 79 ++++++++----------- .../transformations/top-scope/top-scope.js | 4 +- lib/creator/utils/is-assignment.js | 10 --- lib/creator/utils/run-prettier.js | 33 ++++++++ lib/creator/yeoman/webpack-generator.js | 2 +- package.json | 1 + 6 files changed, 70 insertions(+), 59 deletions(-) delete mode 100644 lib/creator/utils/is-assignment.js create mode 100644 lib/creator/utils/run-prettier.js diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 617f45e6827..4f45e884478 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -1,11 +1,9 @@ -const fs = require('fs'); -const chalk = require('chalk'); -const spawn = require('cross-spawn'); -const validateSchema = require('../../utils/validateSchema.js'); -const webpackOptionsSchema = require('../../utils/webpackOptionsSchema.json'); -const WebpackOptionsValidationError = require('../../utils/WebpackOptionsValidationError'); +const path = require('path'); const j = require('jscodeshift'); + const pEachSeries = require('p-each-series'); +const runPrettier = require('../utils/run-prettier'); + const entryTransform = require('./entry/entry'); const outputTransform = require('./output/output'); const contextTransform = require('./context/context'); @@ -61,62 +59,49 @@ const transformsObject = { }; module.exports = function runTransform(webpackProperties) { + + // webpackOptions.name sent to nameTransform if match Object.keys(webpackProperties).forEach( (scaffoldPiece) => { const config = webpackProperties[scaffoldPiece]; + const transformations = Object.keys(transformsObject).map(k => { const stringVal = k.substr(0, k.indexOf('Transform')); - if(config.webpackOptions[stringVal]) { - return [transformsObject[k], config.webpackOptions[stringVal]]; + if(config.webpackOptions) { + if(config.webpackOptions[stringVal]) { + return [transformsObject[k], config.webpackOptions[stringVal]]; + } else { + return [transformsObject[k], config[stringVal]]; + } } else { - return [transformsObject[k], config[stringVal]]; + return [transformsObject[k]]; } }); - let ast = j('module.exports = {}'); + + const ast = j('module.exports = {}'); + return pEachSeries(transformations, f => { - return f[0](j, ast, f[1]); + if(!f[1]) { + return f[0](j, ast); + } else { + return f[0](j, ast, f[1]); + } }) .then(() => { + let configurationName; + if(!config.configName) { + configurationName = 'webpack.config.js'; + } else { + configurationName = 'webpack.' + config.configName + '.js'; + } - const outputPath = process.cwd() + '/webpack.' + (config.configName ? config.configName : 'config') + '.js'; + const outputPath = path.join(process.cwd(), configurationName); const source = ast.toSource({ quote: 'single' }); - const runPrettier = () => { - const processPromise = (child) => { - return new Promise(function(resolve, reject) { //eslint-disable-line - child.addListener('error', reject); - child.addListener('exit', resolve); - }); - }; - const spawnPrettier = () => { - console.log('\n'); - return spawn( - 'prettier', ['--single-quote', '--trailing-comma es5', '--write', outputPath], - { stdio: 'inherit', customFds: [0, 1, 2] } - ); - }; - processPromise(spawnPrettier()).then( () => { - try { - const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, require(outputPath)); - if (webpackOptionsValidationErrors.length) { - const errorMsg = new WebpackOptionsValidationError(webpackOptionsValidationErrors); - throw errorMsg.message; - } else { - process.stdout.write('\n' + chalk.green( - 'Congratulations! Your new webpack config file is created!' - ) + '\n'); - process.exit(0); - } - } catch(err) { - console.log('\n'); - console.error(err); - process.exit(-1); - } - }); - }; - fs.writeFile(outputPath, source, 'utf8', runPrettier); + + runPrettier(outputPath, source); }).catch(err => { - console.error(err); + console.error(err.message ? err.message : err); }); }); }; diff --git a/lib/creator/transformations/top-scope/top-scope.js b/lib/creator/transformations/top-scope/top-scope.js index 49ef0ad42b9..06e681d4577 100644 --- a/lib/creator/transformations/top-scope/top-scope.js +++ b/lib/creator/transformations/top-scope/top-scope.js @@ -16,5 +16,7 @@ module.exports = function(j, ast, webpackProperties) { p.value.body.splice(-1, 0, n); }); } - return ast.find(j.Program).filter(p => createTopScopeProperty(p)); + if(webpackProperties) { + return ast.find(j.Program).filter(p => createTopScopeProperty(p)); + } }; diff --git a/lib/creator/utils/is-assignment.js b/lib/creator/utils/is-assignment.js deleted file mode 100644 index 040ea41822c..00000000000 --- a/lib/creator/utils/is-assignment.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = function(j, p, cb, identifier, property) { - if(p.parent.value.type === 'AssignmentExpression') { - if(j) { - return cb(j, p, identifier, property); - } - else { - return cb(p); - } - } -}; diff --git a/lib/creator/utils/run-prettier.js b/lib/creator/utils/run-prettier.js new file mode 100644 index 00000000000..13c758207d3 --- /dev/null +++ b/lib/creator/utils/run-prettier.js @@ -0,0 +1,33 @@ +const prettier = require('prettier'); +const fs = require('fs'); +const chalk = require('chalk'); + +/* +* +* Runs prettier and later prints the output configuration +* +* @param { String } outputPath - Path to write the config to +* @param { Node } source - AST to write at the given path +* @returns fs - Writes a file at given location and prints messages accordingly +*/ + +module.exports = function runPrettier(outputPath, source) { + function validateConfig() { + let prettySource; + try { + prettySource = prettier.format(source); + process.stdout.write('\n' + chalk.green( + 'Congratulations! Your new webpack configuration file has been created!\n' + + `You can find it at ${outputPath}` + ) + '\n'); + } catch(err) { + process.stdout.write('\n' + + chalk.yellow(`WARNING: Could not apply prettier to ${outputPath}` + + ' due validation error, but the file has been created') + ); + prettySource = source; + } + return fs.writeFileSync(outputPath, prettySource, 'utf8'); + } + return fs.writeFile(outputPath, source, 'utf8', validateConfig); +}; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index c177b9ed4d0..6a02f2fe713 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -34,7 +34,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.dev.webpackOptions.context = 'path.resolve(__dirname, "app")' this.configuration.dev.webpackOptions.resolve = {}; this.configuration.dev.webpackOptions.resolve.alias = {}; - this.configuration.dev.webpackOptions.resolve.alias.hello = ':)' + this.configuration.dev.webpackOptions.resolve.alias.hello = '\':)\'' this.configuration.dev.webpackOptions.resolve.aliasFields = ["'browser'"] this.configuration.dev.webpackOptions.resolve.descriptionFiles = ["'a'", "'b'"] this.configuration.dev.webpackOptions.resolve.enforceExtension = false diff --git a/package.json b/package.json index 596931606ef..b79272aa1f2 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "lodash": "^4.17.4", "p-each-series": "^1.0.0", "p-lazy": "^1.0.0", + "prettier": "^1.2.2", "recast": "git://github.com/kalcifer/recast.git#bug/allowbreak", "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", From 635f2dbb278a2c4936db0cfb743f31ec8216f73a Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 30 Apr 2017 17:49:00 +0200 Subject: [PATCH 077/101] fix: don't print success msg more than one time --- lib/creator/transformations/index.js | 7 ++++++- lib/creator/utils/run-prettier.js | 4 ---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 4f45e884478..9cd7485a498 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -1,7 +1,8 @@ const path = require('path'); const j = require('jscodeshift'); - +const chalk = require('chalk'); const pEachSeries = require('p-each-series'); + const runPrettier = require('../utils/run-prettier'); const entryTransform = require('./entry/entry'); @@ -104,4 +105,8 @@ module.exports = function runTransform(webpackProperties) { console.error(err.message ? err.message : err); }); }); + process.stdout.write('\n' + chalk.green( + 'Congratulations! Your new webpack configuration file has been created!\n' + ) + '\n'); + process.exit(0); }; diff --git a/lib/creator/utils/run-prettier.js b/lib/creator/utils/run-prettier.js index 13c758207d3..b85356ed259 100644 --- a/lib/creator/utils/run-prettier.js +++ b/lib/creator/utils/run-prettier.js @@ -16,10 +16,6 @@ module.exports = function runPrettier(outputPath, source) { let prettySource; try { prettySource = prettier.format(source); - process.stdout.write('\n' + chalk.green( - 'Congratulations! Your new webpack configuration file has been created!\n' + - `You can find it at ${outputPath}` - ) + '\n'); } catch(err) { process.stdout.write('\n' + chalk.yellow(`WARNING: Could not apply prettier to ${outputPath}` + From b32e7a2cef75af513608c5a24a424cd9ab80ce09 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 30 Apr 2017 20:34:52 +0200 Subject: [PATCH 078/101] enhancements: fix windows paths --- lib/creator/transformations/index.js | 3 +-- lib/creator/utils/run-prettier.js | 2 +- lib/utils/resolve-packages.js | 21 +++++++++++---------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/lib/creator/transformations/index.js b/lib/creator/transformations/index.js index 9cd7485a498..779bede11c6 100644 --- a/lib/creator/transformations/index.js +++ b/lib/creator/transformations/index.js @@ -107,6 +107,5 @@ module.exports = function runTransform(webpackProperties) { }); process.stdout.write('\n' + chalk.green( 'Congratulations! Your new webpack configuration file has been created!\n' - ) + '\n'); - process.exit(0); + )); }; diff --git a/lib/creator/utils/run-prettier.js b/lib/creator/utils/run-prettier.js index b85356ed259..b21ece7242b 100644 --- a/lib/creator/utils/run-prettier.js +++ b/lib/creator/utils/run-prettier.js @@ -19,7 +19,7 @@ module.exports = function runPrettier(outputPath, source) { } catch(err) { process.stdout.write('\n' + chalk.yellow(`WARNING: Could not apply prettier to ${outputPath}` + - ' due validation error, but the file has been created') + ' due validation error, but the file has been created\n') ); prettySource = source; } diff --git a/lib/utils/resolve-packages.js b/lib/utils/resolve-packages.js index 0f2a8c59e4e..52f3b3e7db0 100644 --- a/lib/utils/resolve-packages.js +++ b/lib/utils/resolve-packages.js @@ -15,8 +15,11 @@ const globalPath = require('global-modules'); function processPromise(child) { return new Promise(function(resolve, reject) { //eslint-disable-line - child.addListener('error', reject); - child.addListener('exit', resolve); + if(child.status !== 0) { + reject(); + } else { + resolve(); + } }); } @@ -30,15 +33,14 @@ function processPromise(child) { */ function spawnChild(pkg) { - // Different for windows, needs fix - const pkgPath = path.join(globalPath, '/', pkg); + const pkgPath = path.resolve(globalPath, pkg); + let installType; if(fs.existsSync(pkgPath)) { - // HACK / FIXME -> npm update right away doesn't install the updated pkg. - spawn('rm', ['-rf', pkgPath], { stdio: 'inherit', customFds: [0, 1, 2] }); - return spawn('npm', ['install', '-g', pkg], { stdio: 'inherit', customFds: [0, 1, 2] }); + installType = 'update'; } else { - return spawn('npm', ['install', '-g', pkg], { stdio: 'inherit', customFds: [0, 1, 2] }); + installType = 'install'; } + return spawn.sync('npm', [installType, '-g', pkg], { stdio: 'inherit'}); } /* @@ -59,8 +61,7 @@ module.exports = function resolvePackages(pkg) { pkg.forEach( (addon) => { processPromise(spawnChild(addon)).then( () => { try { - // Different for windows, needs fix - packageLocations.push(path.join(globalPath, '/', addon)); + packageLocations.push(path.resolve(globalPath, addon)); } catch(err) { console.log('Package wasn\'t validated correctly..'); console.log('Submit an issue for', pkg, 'if this persists'); From b6c09261bedd834b81a083c70d7c2cbbd6de4a9a Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 30 Apr 2017 20:41:42 +0200 Subject: [PATCH 079/101] Webpack-CLI Documentation (#112) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: init * chore: add section about init and migrate * chore: add migrate and scaffold link * Create SCAFFOLDING.md * Create MIGRATE.md * chore: add docs on scaffolding * chore: add initial on addons * chore: fix initial documentation Also fixes some text at «Scaffolding» * chore: revise section on good scaffold * chore: add some API docs * chore: rephrase docs * chore: syntax sugar * chore: more syntax sugar * chore: lint webpack-cli properly --- MIGRATE.md | 1 + README.md | 19 +++++++++--- SCAFFOLDING.md | 83 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 MIGRATE.md create mode 100644 SCAFFOLDING.md diff --git a/MIGRATE.md b/MIGRATE.md new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/MIGRATE.md @@ -0,0 +1 @@ + diff --git a/README.md b/README.md index cfe291bcb49..16b9b078b4b 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,22 @@ # Webpack CLI -This project intends to be the main cli package of webpack. Here we will encapsulate all the features and code related to the command line. From sending options to the compiler, to initialize and migrate from version to version. +Webpack CLI encapsulates all code related to CLI handling. It captures options and sends them to webpack compiler. You can also find functionality for initializing a project and migrating between versions. For the time being, it is backwards-compatible with the CLI included in webpack itself. **Note** The package is still in work in progress. In case you want to contribute, reach to us, so we can point you out how and when you can help us. +## Migration from webpack v1 to v2 -# Roadmap to the first release +The `migrate` feature eases the transition from [version 1](http://webpack.github.io/docs/) to [version 2](https://gist.github.com/sokra/27b24881210b56bbaff7). `migrate` also allows users to switch to the new version of webpack without having to extensively [refactor](https://webpack.js.org/guides/migrating/). -- Migrate to webpack-cli all the current cli options available in webpack -- Create a `webpack-cli init` command that serves to set a configuration of webpack to the user -- create a `webpack-cli migrate` command that serves to migrate an existing configuration from webpack 1 to webpack 2. +`webpack --migrate ` + +[Read more about migrating](MIGRATE.md) + +## Creating new webpack projects + +The `init` feature allows users to get started with webpack, fast. Through scaffolding, people can create their own configuration in order to faster initialize new projects for various of use cases. + +`webpack --init [webpack-addons-]` + +[Read more about scaffolding](SCAFFOLDING.md) diff --git a/SCAFFOLDING.md b/SCAFFOLDING.md new file mode 100644 index 00000000000..de17fcd641a --- /dev/null +++ b/SCAFFOLDING.md @@ -0,0 +1,83 @@ +# Introduction + +Setting up webpack for the first time is hard. Writing advanced configurations to optimize performance is even harder. The `init` feature is designed to support people that want to create their own configuration or initializing other projects people create. + +Through [yeoman](http://yeoman.io/), the `webpack --init` feature allows people to create scaffolds and generate new projects quickly. An npm dependency that scaffolds a `webpack.config.js` through `webpack-cli` is what we refer to as an **addon**. + +## Writing a good scaffold + +Before writing a `webpack-cli` scaffold, think about what you're trying to achieve. Do you want a "general" scaffold that could be used by any project or type of app? Do you want something very focused - like a scaffold that writes both your `webpack.config.js` and your framework code? It's also useful to think about the user experience for your scaffold. + +`webpack-cli` offers an experience that is interactive and you can prompt users for questions (like, "What is your entry point?") to help customize the output accordingly. + +## webpack-addons + +[`webpack-addons`](https://github.com/webpack-contrib/webpack-addons) is a utility suite for creating addons. It contains functions that could be of use for creating an addon yourself. + +## webpack-addons-yourpackage + +In order for `webpack-cli` to compile your package, it relies on a prefix of `webpack-addons`. The package must also be published on npm. If you are curious about how you can create your very own `addon`, please read [How do I compose a webpack-addon?](https://github.com/ev1stensberg/webpack-addons-demo). + +## API + +To create an `addon`, you must create a [`yeoman-generator`](http://yeoman.io/authoring/). Because of that, you can optionally extend your generator to include methods from the [Yeoman API](http://yeoman.io/learning/). Its worth noting that we support all the properties of a regular webpack configuration. In order for us to do this, there's a thing you need to remember. + +Objects are made using strings, while strings are made using double strings. This means that in order for you to create an string, you have to wrap it inside another string for us to validate it correctly. + + +### `opts.env.configuration`(Required) + +Initialized inside the constructor of your generator in order for the CLI to work. + +```js +constructor(args, opts) { + super(args, opts); + opts.env.configuration = {}; + } +``` +### `opts.env.configuration.myObj` (required) + +`myObj` is your scaffold. This is where you will add options for the CLI to transform into a configuration. You can name it anything, and you can also add more objects, that could represent a `dev.config` or `prod.config`. + +```js +constructor(args, opts) { + super(args, opts); + opts.env.configuration = { + dev: {}, + prod: {} + }; + } +``` + +### `myObj.webpackOptions` (required) + +As with a regular webpack configuration, this property behaves the same. Inside `webpackOptions` you can declare the properties you want to scaffold. You can for instance, scaffold `entry`, `output` and `context`. + +(Inside a yeoman method) +```js +this.options.env.configuration.dev.webpackOptions = { +entry: '\'app.js\'', +output: {....}, +merge: 'myConfig' +}; +``` +If you want to use `webpack-merge`, you can supply `webpackOptions` with the merge property, and the configuration you want to merge it with. + +### `myObj.topScope`(optional) + +The `topScope` property is a way for the authors to add special behaviours, like functions that could be called inside a configuration, or variable initializations and module imports. + +```js +this.options.env.configuration.dev.topScope = [ +'var webpack = require(\'webpack\');' +'var path = require(\'path\');' +]; +``` + +### `myObj.configName`(optional) + +If you want to name your `webpack.config.js` something special, you can do that. + +```js +this.options.env.configuration.dev.configName = 'base'; +``` From cdd5fb455afd2c101c771f624121df74717c21ec Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 30 Apr 2017 20:58:10 +0200 Subject: [PATCH 080/101] chore: prepare to update webpack/bin to ours --- bin/config-optimist.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 bin/config-optimist.js diff --git a/bin/config-optimist.js b/bin/config-optimist.js new file mode 100644 index 00000000000..e69de29bb2d From cd5562cf2bedd8db6f407ea21383bf495afb2cfa Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 30 Apr 2017 21:46:12 +0200 Subject: [PATCH 081/101] chore: refactor against webpack/lib --- bin/config-optimist.js | 0 bin/config-yargs.js | 12 +- bin/convert-argv.js | 43 +++--- bin/webpack.js | 262 ++++++++++++++++++++++++++++++---- example/neo-webpack.config.js | 20 --- example/webpack.config.js | 20 --- 6 files changed, 253 insertions(+), 104 deletions(-) delete mode 100644 bin/config-optimist.js delete mode 100644 example/neo-webpack.config.js delete mode 100644 example/webpack.config.js diff --git a/bin/config-optimist.js b/bin/config-optimist.js deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/bin/config-yargs.js b/bin/config-yargs.js index a9363f40659..e75d9b7b5f3 100644 --- a/bin/config-yargs.js +++ b/bin/config-yargs.js @@ -33,7 +33,7 @@ module.exports = function(yargs) { requiresArg: true }, 'env': { - describe: 'Enviroment passed to the config, when it is a function', + describe: 'Environment passed to the config, when it is a function', group: CONFIG_GROUP }, 'context': { @@ -149,7 +149,7 @@ module.exports = function(yargs) { }, 'target': { type: 'string', - describe: 'The targeted execution enviroment', + describe: 'The targeted execution environment', group: ADVANCED_GROUP, requiresArg: true }, @@ -166,12 +166,6 @@ module.exports = function(yargs) { describe: 'Watch the filesystem for changes', group: BASIC_GROUP }, - 'save': { - type: 'boolean', - alias: 's', - describe: 'Rebuilds on save regardless of changes in watch mode', - group: BASIC_GROUP - }, 'watch-stdin': { type: 'boolean', alias: 'stdin', @@ -185,7 +179,7 @@ module.exports = function(yargs) { }, 'watch-poll': { type: 'boolean', - describe: 'The polling intervall for watching (also enable polling)', + describe: 'The polling interval for watching (also enable polling)', group: ADVANCED_GROUP }, 'hot': { diff --git a/bin/convert-argv.js b/bin/convert-argv.js index e3e004f652b..190ab8a9b0a 100644 --- a/bin/convert-argv.js +++ b/bin/convert-argv.js @@ -122,7 +122,7 @@ module.exports = function(yargs, argv, convertOptions) { function processConfiguredOptions(options) { if(options === null || typeof options !== 'object') { console.error('Config did not export an object or a function returning an object.'); - process.exit(-1); + process.exit(-1); // eslint-disable-line } // process Promise @@ -224,16 +224,10 @@ module.exports = function(yargs, argv, convertOptions) { options[optionName || name] = false; }); } - //eslint-disable-next-line - function mapArgToPath(name, optionName) { - ifArg(name, function(str) { - options[optionName || name] = path.resolve(str); - }); - } function loadPlugin(name) { var loadUtils = require('loader-utils'); - var args = null; + var args; try { var p = name && name.indexOf('?'); if(p > -1) { @@ -242,7 +236,7 @@ module.exports = function(yargs, argv, convertOptions) { } } catch(e) { console.log('Invalid plugin arguments ' + name + ' (' + e + ').'); - process.exit(-1); + process.exit(-1); // eslint-disable-line } var path; @@ -251,7 +245,7 @@ module.exports = function(yargs, argv, convertOptions) { path = resolve.sync(process.cwd(), name); } catch(e) { console.log('Cannot resolve plugin ' + name + '.'); - process.exit(-1); + process.exit(-1); // eslint-disable-line } var Plugin; try { @@ -281,7 +275,11 @@ module.exports = function(yargs, argv, convertOptions) { } ifArgPair('entry', function(name, entry) { - options.entry[name] = entry; + if(typeof options.entry[name] !== 'undefined' && options.entry[name] !== null) { + options.entry[name] = [].concat(options.entry[name]).concat(entry); + } else { + options.entry[name] = entry; + } }, function() { ensureObject(options, 'entry'); }); @@ -322,7 +320,7 @@ module.exports = function(yargs, argv, convertOptions) { ifArg('output-path', function(value) { ensureObject(options, 'output'); - options.output.path = value; + options.output.path = path.resolve(value); }); ifArg('output-filename', function(value) { @@ -454,7 +452,7 @@ module.exports = function(yargs, argv, convertOptions) { ifArg('prefetch', function(request) { ensureArray(options, 'plugins'); - var PrefetchPlugin = require('webpack/PrefetchPlugin'); + var PrefetchPlugin = require('webpack/lib/PrefetchPlugin'); options.plugins.push(new PrefetchPlugin(request)); }); @@ -468,16 +466,10 @@ module.exports = function(yargs, argv, convertOptions) { } else { name = value; } - var ProvidePlugin = require('webpack/ProvidePlugin'); + var ProvidePlugin = require('webpack/lib/ProvidePlugin'); options.plugins.push(new ProvidePlugin(name, value)); }); - ifBooleanArg('labeled-modules', function() { - ensureArray(options, 'plugins'); - var LabeledModulesPlugin = require('webpack/lib/dependencies/LabeledModulesPlugin'); - options.plugins.push(new LabeledModulesPlugin()); - }); - ifArg('plugin', function(value) { ensureArray(options, 'plugins'); options.plugins.push(loadPlugin(value)); @@ -490,19 +482,20 @@ module.exports = function(yargs, argv, convertOptions) { if(noOutputFilenameDefined) { ensureObject(options, 'output'); if(convertOptions && convertOptions.outputFilename) { - options.output.path = path.dirname(convertOptions.outputFilename); + options.output.path = path.resolve(path.dirname(convertOptions.outputFilename)); options.output.filename = path.basename(convertOptions.outputFilename); } else if(argv._.length > 0) { options.output.filename = argv._.pop(); - options.output.path = path.dirname(options.output.filename); + options.output.path = path.resolve(path.dirname(options.output.filename)); options.output.filename = path.basename(options.output.filename); } else if(configFileLoaded) { throw new Error('\'output.filename\' is required, either in config file or as --output-filename'); - } else { + } + else { console.error('No configuration file found and no output filename configured via CLI option.'); console.error('A configuration file could be named \'webpack.config.js\' in the current directory.'); console.error('Use --help to display the CLI options.'); - process.exit(-1); + process.exit(-1); // eslint-disable-line } } @@ -549,7 +542,7 @@ module.exports = function(yargs, argv, convertOptions) { console.error('A configuration file could be named \'webpack.config.js\' in the current directory.'); } console.error('Use --help to display the CLI options.'); - process.exit(-1); + process.exit(-1); // eslint-disable-line } } }; diff --git a/bin/webpack.js b/bin/webpack.js index 1a5a67aac00..6320b20aea2 100755 --- a/bin/webpack.js +++ b/bin/webpack.js @@ -5,41 +5,24 @@ Author Tobias Koppers @sokra */ var path = require('path'); -// var fs = require('fs'); -// Local version replace global one - -process.title = 'webpack'; +// Local version replace global one try { - var localWebpack = require.resolve(path.join(process.cwd(), 'node_modules', 'webpack-cli', 'bin', 'webpack.js')); - if(localWebpack && path.relative(localWebpack, __filename) !== '') { + var localWebpack = require.resolve(path.join(process.cwd(), 'node_modules', + 'webpack', 'node_modules', 'webpack-cli', 'bin', 'webpack.js')); + if(__filename !== localWebpack) { return require(localWebpack); - } -} catch(e) { - /* - // Delete Cache, Retry and leave it if the path isn`t valid. - // swap with webpack-cli later - var dirPath = path.join(process.cwd(), 'node_modules', 'webpack', 'bin'); - var retryLocal; - fs.readdir(dirPath, function(err, files) { - files.filter( (file) => { - delete require.cache[file]; - }); - - // TODO: If path is wrong, leave it to higher powers until we publish on npm - // Could also install and load and install through github - return require(path.join(dirPath, 'webpack.js')) - }); - */ -} + } //eslint-disable-next-line +} catch(e) {} var yargs = require('yargs') - .usage('webpack-cli ' + require('../package.json').version + '\n' + - 'Usage: https://webpack.github.io/docs/cli.html\n' + + .usage('webpack ' + require('../package.json').version + '\n' + + 'Usage: https://webpack.js.org/api/cli/\n' + 'Usage without config file: webpack [] \n' + 'Usage with config file: webpack'); require('./config-yargs')(yargs); + var DISPLAY_GROUP = 'Stats options:'; var BASIC_GROUP = 'Basic options:'; @@ -93,6 +76,11 @@ yargs.options({ group: DISPLAY_GROUP, describe: 'Display even excluded modules in the output' }, + 'display-max-modules': { + type: 'number', + group: DISPLAY_GROUP, + describe: 'Sets the maximum number of visible modules in output' + }, 'display-chunks': { type: 'boolean', group: DISPLAY_GROUP, @@ -123,6 +111,11 @@ yargs.options({ group: DISPLAY_GROUP, describe: 'Display reasons about module inclusion in the output' }, + 'display-depth': { + type: 'boolean', + group: DISPLAY_GROUP, + describe: 'Display distance from entry point for each module' + }, 'display-used-exports': { type: 'boolean', group: DISPLAY_GROUP, @@ -149,6 +142,7 @@ var argv = yargs.argv; if(argv.verbose) { argv['display-reasons'] = true; + argv['display-depth'] = true; argv['display-entrypoints'] = true; argv['display-used-exports'] = true; argv['display-provided-exports'] = true; @@ -157,16 +151,224 @@ if(argv.verbose) { argv['display-cached'] = true; argv['display-cached-assets'] = true; } - if(argv.init) { - require('../lib/initialize')(argv._); + return require('../lib/initialize')(argv._); } else if(argv.migrate) { const filePaths = argv._; if (!filePaths.length) { throw new Error('Please specify a path to your webpack config'); } const inputConfigPath = path.resolve(process.cwd(), filePaths[0]); - require('../lib/migrate.js')(inputConfigPath, inputConfigPath); + return require('../lib/migrate.js')(inputConfigPath, inputConfigPath); } else { - require('./process-options')(yargs,argv); + var options = require('./convert-argv')(yargs, argv); + return processOptions(options); +} + +function ifArg(name, fn, init) { + if(Array.isArray(argv[name])) { + if(init) init(); + argv[name].forEach(fn); + } else if(typeof argv[name] !== 'undefined') { + if(init) init(); + fn(argv[name], -1); + } +} +//eslint-disable-next-line +function processOptions(options) { + // process Promise + if(typeof options.then === 'function') { + options.then(processOptions).catch(function(err) { + console.error(err.stack || err); + process.exit(1); // eslint-disable-line + }); + return; + } + + var firstOptions = [].concat(options)[0]; + var statsPresetToOptions = require('webpack/lib/Stats.js').presetToOptions; + + var outputOptions = options.stats; + if(typeof outputOptions === 'boolean' || typeof outputOptions === 'string') { + outputOptions = statsPresetToOptions(outputOptions); + } else if(!outputOptions) { + outputOptions = {}; + } + outputOptions = Object.create(outputOptions); + if(Array.isArray(options) && !outputOptions.children) { + outputOptions.children = options.map(o => o.stats); + } + if(typeof outputOptions.context === 'undefined') + outputOptions.context = firstOptions.context; + + ifArg('json', function(bool) { + if(bool) + outputOptions.json = bool; + }); + + if(typeof outputOptions.colors === 'undefined') + outputOptions.colors = require('supports-color'); + + ifArg('sort-modules-by', function(value) { + outputOptions.modulesSort = value; + }); + + ifArg('sort-chunks-by', function(value) { + outputOptions.chunksSort = value; + }); + + ifArg('sort-assets-by', function(value) { + outputOptions.assetsSort = value; + }); + + ifArg('display-exclude', function(value) { + outputOptions.exclude = value; + }); + + if(!outputOptions.json) { + if(typeof outputOptions.cached === 'undefined') + outputOptions.cached = false; + if(typeof outputOptions.cachedAssets === 'undefined') + outputOptions.cachedAssets = false; + + ifArg('display-chunks', function(bool) { + outputOptions.modules = !bool; + outputOptions.chunks = bool; + }); + + ifArg('display-entrypoints', function(bool) { + outputOptions.entrypoints = bool; + }); + + ifArg('display-reasons', function(bool) { + outputOptions.reasons = bool; + }); + + ifArg('display-depth', function(bool) { + outputOptions.depth = bool; + }); + + ifArg('display-used-exports', function(bool) { + outputOptions.usedExports = bool; + }); + + ifArg('display-provided-exports', function(bool) { + outputOptions.providedExports = bool; + }); + + ifArg('display-error-details', function(bool) { + outputOptions.errorDetails = bool; + }); + + ifArg('display-origins', function(bool) { + outputOptions.chunkOrigins = bool; + }); + + ifArg('display-max-modules', function(value) { + outputOptions.maxModules = value; + }); + + ifArg('display-cached', function(bool) { + if(bool) + outputOptions.cached = true; + }); + + ifArg('display-cached-assets', function(bool) { + if(bool) + outputOptions.cachedAssets = true; + }); + + if(!outputOptions.exclude) + outputOptions.exclude = ['node_modules', 'bower_components', 'components']; + + if(argv['display-modules']) { + outputOptions.maxModules = Infinity; + outputOptions.exclude = undefined; + } + } else { + if(typeof outputOptions.chunks === 'undefined') + outputOptions.chunks = true; + if(typeof outputOptions.entrypoints === 'undefined') + outputOptions.entrypoints = true; + if(typeof outputOptions.modules === 'undefined') + outputOptions.modules = true; + if(typeof outputOptions.chunkModules === 'undefined') + outputOptions.chunkModules = true; + if(typeof outputOptions.reasons === 'undefined') + outputOptions.reasons = true; + if(typeof outputOptions.cached === 'undefined') + outputOptions.cached = true; + if(typeof outputOptions.cachedAssets === 'undefined') + outputOptions.cachedAssets = true; + } + + ifArg('hide-modules', function(bool) { + if(bool) { + outputOptions.modules = false; + outputOptions.chunkModules = false; + } + }); + + var webpack = require('webpack/lib/webpack.js'); + + Error.stackTraceLimit = 30; + var lastHash = null; + var compiler; + try { + compiler = webpack(options); + } catch(e) { + var WebpackOptionsValidationError = require('webpack/lib/WebpackOptionsValidationError'); + if(e instanceof WebpackOptionsValidationError) { + if(argv.color) + console.error('\u001b[1m\u001b[31m' + e.message + '\u001b[39m\u001b[22m'); + else + console.error(e.message); + process.exit(1); // eslint-disable-line no-process-exit + } + throw e; + } + + if(argv.progress) { + var ProgressPlugin = require('webpack/lib/ProgressPlugin'); + compiler.apply(new ProgressPlugin({ + profile: argv.profile + })); + } + + function compilerCallback(err, stats) { + if(!options.watch || err) { + // Do not keep cache anymore + compiler.purgeInputFileSystem(); + } + if(err) { + lastHash = null; + console.error(err.stack || err); + if(err.details) console.error(err.details); + process.exit(1); // eslint-disable-line + } + if(outputOptions.json) { + process.stdout.write(JSON.stringify(stats.toJson(outputOptions), null, 2) + '\n'); + } else if(stats.hash !== lastHash) { + lastHash = stats.hash; + process.stdout.write(stats.toString(outputOptions) + '\n'); + } + if(!options.watch && stats.hasErrors()) { + process.on('exit', function() { + process.exit(2); // eslint-disable-line + }); + } + } + if(firstOptions.watch || options.watch) { + var watchOptions = firstOptions.watchOptions || firstOptions.watch || options.watch || {}; + if(watchOptions.stdin) { + process.stdin.on('end', function() { + process.exit(0); // eslint-disable-line + }); + process.stdin.resume(); + } + compiler.watch(watchOptions, compilerCallback); + console.log('\nWebpack is watching the files…\n'); + } else + compiler.run(compilerCallback); + } diff --git a/example/neo-webpack.config.js b/example/neo-webpack.config.js deleted file mode 100644 index 458a1fd7f48..00000000000 --- a/example/neo-webpack.config.js +++ /dev/null @@ -1,20 +0,0 @@ -var path = require('path'); - - -module.exports = { - devtool: 'eval', - entry: [ - './src/index' - ], - output: { - path: path.join(__dirname, 'dist'), - filename: 'index.js' - }, - module: { - rules: [{ - test: /\.js$/, - use: ['babel'], - include: path.join(__dirname, 'src') - }] - } -}; diff --git a/example/webpack.config.js b/example/webpack.config.js deleted file mode 100644 index d0dd7933a45..00000000000 --- a/example/webpack.config.js +++ /dev/null @@ -1,20 +0,0 @@ -var path = require('path'); - - -module.exports = { - devtool: 'eval', - entry: [ - './src/index' - ], - output: { - path: path.join(__dirname, 'dist'), - filename: 'index.js' - }, - module: { - loaders: [{ - test: /\.js$/, - loaders: ['babel'], - include: path.join(__dirname, 'src') - }] - } -}; From 63c30ca64f32d4a27071bb6cc56e5c1c37e11359 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 30 Apr 2017 21:49:08 +0200 Subject: [PATCH 082/101] remove shebang --- bin/webpack.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/bin/webpack.js b/bin/webpack.js index 6320b20aea2..08423354908 100755 --- a/bin/webpack.js +++ b/bin/webpack.js @@ -1,5 +1,3 @@ -#!/usr/bin/env node - /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra From bde984fff82478f3bf46fe890a641bc514347641 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 30 Apr 2017 23:40:37 +0200 Subject: [PATCH 083/101] chore: remove old rx code --- lib/creator/utils/validate-options.js | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/lib/creator/utils/validate-options.js b/lib/creator/utils/validate-options.js index be76787e0f8..03c2fadb8bb 100644 --- a/lib/creator/utils/validate-options.js +++ b/lib/creator/utils/validate-options.js @@ -35,25 +35,3 @@ module.exports = function validateOptions(opts) { } }); }; -/* - -const fs = require('fs'); -const path = require('path'); -const Rx = require('rxjs'); - -function getPath(part) { - return path.join(process.cwd(), part); -} - -const readFileObservable = Rx.Observable.bindNodeCallback(fs.readFileSync); - -module.exports = function validateOptions(opts) { - return Rx.Observable.pairs(opts) - .map(([, opt]) => getPath(opt)) - .flatMap(part => readFileObservable(part)) - .then(part, err => { - console.error('Found no file at:', part); - }); -}; - -*/ From 042fc7cffa0b0e5d1b941b5b4fc704a25e28c9f9 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Mon, 1 May 2017 23:57:41 +0200 Subject: [PATCH 084/101] enhancements: default generator and exitCode Introduces a default generator and swapped exitCode(0) with exitCode = --- bin/convert-argv.js | 10 +- bin/process-options.js | 8 +- bin/webpack.js | 11 +- lib/creator/index.js | 3 +- lib/creator/utils/run-prettier.js | 6 +- lib/creator/utils/validate-options.js | 2 +- lib/creator/yeoman/utils/entry.js | 50 ++++++ lib/creator/yeoman/utils/module.js | 16 ++ lib/creator/yeoman/utils/output.js | 16 ++ lib/creator/yeoman/utils/plugins.js | 5 + lib/creator/yeoman/webpack-generator.js | 198 +++++++++--------------- lib/utils/resolve-packages.js | 4 +- 12 files changed, 186 insertions(+), 143 deletions(-) create mode 100644 lib/creator/yeoman/utils/entry.js create mode 100644 lib/creator/yeoman/utils/module.js create mode 100644 lib/creator/yeoman/utils/output.js create mode 100644 lib/creator/yeoman/utils/plugins.js diff --git a/bin/convert-argv.js b/bin/convert-argv.js index 190ab8a9b0a..cd16639191f 100644 --- a/bin/convert-argv.js +++ b/bin/convert-argv.js @@ -122,7 +122,7 @@ module.exports = function(yargs, argv, convertOptions) { function processConfiguredOptions(options) { if(options === null || typeof options !== 'object') { console.error('Config did not export an object or a function returning an object.'); - process.exit(-1); // eslint-disable-line + process.exitCode = -1; } // process Promise @@ -236,7 +236,7 @@ module.exports = function(yargs, argv, convertOptions) { } } catch(e) { console.log('Invalid plugin arguments ' + name + ' (' + e + ').'); - process.exit(-1); // eslint-disable-line + process.exitCode = -1; } var path; @@ -245,7 +245,7 @@ module.exports = function(yargs, argv, convertOptions) { path = resolve.sync(process.cwd(), name); } catch(e) { console.log('Cannot resolve plugin ' + name + '.'); - process.exit(-1); // eslint-disable-line + process.exitCode = -1; } var Plugin; try { @@ -495,7 +495,7 @@ module.exports = function(yargs, argv, convertOptions) { console.error('No configuration file found and no output filename configured via CLI option.'); console.error('A configuration file could be named \'webpack.config.js\' in the current directory.'); console.error('Use --help to display the CLI options.'); - process.exit(-1); // eslint-disable-line + process.exitCode = -1; } } @@ -542,7 +542,7 @@ module.exports = function(yargs, argv, convertOptions) { console.error('A configuration file could be named \'webpack.config.js\' in the current directory.'); } console.error('Use --help to display the CLI options.'); - process.exit(-1); // eslint-disable-line + process.exitCode = -1; } } }; diff --git a/bin/process-options.js b/bin/process-options.js index 764c560546d..e97bb5af4c6 100644 --- a/bin/process-options.js +++ b/bin/process-options.js @@ -139,7 +139,7 @@ module.exports = function processOptions(yargs, argv) { console.error('\u001b[1m\u001b[31m' + e.message + '\u001b[39m\u001b[22m'); else console.error(e.message); - process.exit(1); + process.exitCode = 1; } throw e; } @@ -160,7 +160,7 @@ module.exports = function processOptions(yargs, argv) { lastHash = null; console.error(err.stack || err); if(err.details) console.error(err.details); - process.exit(1); + process.exitCode = 1; } if(outputOptions.json) { process.stdout.write(JSON.stringify(stats.toJson(outputOptions), null, 2) + '\n'); @@ -172,7 +172,7 @@ module.exports = function processOptions(yargs, argv) { } if(!options.watch && stats.hasErrors()) { process.on('exit', function() { - process.exit(2); + process.exitCode = 2; }); } } @@ -181,7 +181,7 @@ module.exports = function processOptions(yargs, argv) { var watchOptions = primaryOptions.watchOptions || primaryOptions.watch || {}; if(watchOptions.stdin) { process.stdin.on('end', function() { - process.exit(0); + process.exitCode = 0; }); process.stdin.resume(); } diff --git a/bin/webpack.js b/bin/webpack.js index 08423354908..6ba04c67ee9 100755 --- a/bin/webpack.js +++ b/bin/webpack.js @@ -17,7 +17,6 @@ var yargs = require('yargs') 'Usage: https://webpack.js.org/api/cli/\n' + 'Usage without config file: webpack [] \n' + 'Usage with config file: webpack'); - require('./config-yargs')(yargs); @@ -178,7 +177,7 @@ function processOptions(options) { if(typeof options.then === 'function') { options.then(processOptions).catch(function(err) { console.error(err.stack || err); - process.exit(1); // eslint-disable-line + process.exitCode = -1; }); return; } @@ -321,7 +320,7 @@ function processOptions(options) { console.error('\u001b[1m\u001b[31m' + e.message + '\u001b[39m\u001b[22m'); else console.error(e.message); - process.exit(1); // eslint-disable-line no-process-exit + process.exitCode = 1; } throw e; } @@ -342,7 +341,7 @@ function processOptions(options) { lastHash = null; console.error(err.stack || err); if(err.details) console.error(err.details); - process.exit(1); // eslint-disable-line + process.exitCode = 1; } if(outputOptions.json) { process.stdout.write(JSON.stringify(stats.toJson(outputOptions), null, 2) + '\n'); @@ -352,7 +351,7 @@ function processOptions(options) { } if(!options.watch && stats.hasErrors()) { process.on('exit', function() { - process.exit(2); // eslint-disable-line + process.exitCode = 2; }); } } @@ -360,7 +359,7 @@ function processOptions(options) { var watchOptions = firstOptions.watchOptions || firstOptions.watch || options.watch || {}; if(watchOptions.stdin) { process.stdin.on('end', function() { - process.exit(0); // eslint-disable-line + process.exitCode = 0; }); process.stdin.resume(); } diff --git a/lib/creator/index.js b/lib/creator/index.js index cf8fdc5894d..cd3174edf14 100644 --- a/lib/creator/index.js +++ b/lib/creator/index.js @@ -31,8 +31,7 @@ function creator(options) { env.registerStub(defaultGenerator, 'webpack-default-generator'); } - env.run(generatorName) - .on('end', () => { + env.run(generatorName).on('end', () => { if(generatorName !== 'webpack-default-generator') { //HACK / FIXME env = env.options.env; diff --git a/lib/creator/utils/run-prettier.js b/lib/creator/utils/run-prettier.js index b21ece7242b..59f60b0e161 100644 --- a/lib/creator/utils/run-prettier.js +++ b/lib/creator/utils/run-prettier.js @@ -15,7 +15,11 @@ module.exports = function runPrettier(outputPath, source) { function validateConfig() { let prettySource; try { - prettySource = prettier.format(source); + prettySource = prettier.format(source, { + singleQuote: true, + useTabs: true, + tabWidth: 1, + }); } catch(err) { process.stdout.write('\n' + chalk.yellow(`WARNING: Could not apply prettier to ${outputPath}` + diff --git a/lib/creator/utils/validate-options.js b/lib/creator/utils/validate-options.js index 03c2fadb8bb..111bebd428b 100644 --- a/lib/creator/utils/validate-options.js +++ b/lib/creator/utils/validate-options.js @@ -31,7 +31,7 @@ module.exports = function validateOptions(opts) { fs.readFileSync(part); } catch (err) { console.error('Found no file at:', part); - process.exit(1); + process.exitCode = 1; } }); }; diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js new file mode 100644 index 00000000000..79c9d29c2d2 --- /dev/null +++ b/lib/creator/yeoman/utils/entry.js @@ -0,0 +1,50 @@ +const Input = require('webpack-addons').Input; + +module.exports = (self, answer) => { + return new Promise( (resolve, reject) => { + let webpackEntryPoint; + + let entryIdentifiers; + let entryProperties; + if(answer['entryType'].indexOf('Array') >= 0) { + self.prompt([ + Input('arrayNumber', 'write your entry points seperated by comma') + ]).then( (arrayAnswer) => { + webpackEntryPoint = arrayAnswer['arrayNumber'].split(','); + resolve(webpackEntryPoint.map( (prop) => { + let newProp = `'${prop}'`; + return newProp; + })); + }); + } + else if(answer['entryType'].indexOf('Object') >= 0) { + self.prompt([ + Input('objectNames', 'List your entry properties seperated by comma') + ]).then( (objectIdentifierAnswer) => { + webpackEntryPoint = {}; + entryIdentifiers = objectIdentifierAnswer['objectNames'].split(','); + self.prompt([ + Input('objectProperties', 'List your entry properties seperated by comma') + ]).then( (objectPropAnswer) => { + entryProperties = objectPropAnswer['objectProperties'].split(','); + for(let k = 0; k < entryIdentifiers.length; k++) { + webpackEntryPoint[entryIdentifiers[k]] = `'${entryProperties[k]}'`; + } + resolve(webpackEntryPoint); + }); + }); + } + else { + self.prompt([ + Input('singularEntry', 'What\'s your entry point?') + ]).then( (singularAnswer) => { + if(answer['entryType'].indexOf('String') >= 0) { + webpackEntryPoint = `'${singularAnswer['singularEntry']}'`; + } else { + webpackEntryPoint = singularAnswer['singularEntry']; + } + resolve(webpackEntryPoint); + }); + } + }); +}; diff --git a/lib/creator/yeoman/utils/module.js b/lib/creator/yeoman/utils/module.js new file mode 100644 index 00000000000..5949599e56a --- /dev/null +++ b/lib/creator/yeoman/utils/module.js @@ -0,0 +1,16 @@ +module.exports = () => { + return { + rules: [ + { + test: new RegExp(/\.js$/), + exclude: '/node_modules/', + loader: '\'babel-loader\'', + options: { + presets: [ + '\'es2015\'' + ] + } + } + ] + }; +}; diff --git a/lib/creator/yeoman/utils/output.js b/lib/creator/yeoman/utils/output.js new file mode 100644 index 00000000000..86e5608e445 --- /dev/null +++ b/lib/creator/yeoman/utils/output.js @@ -0,0 +1,16 @@ +const Input = require('webpack-addons').Input; + +module.exports = (self, answer) => { + return new Promise( (resolve, reject) => { + let webpackOutputPoint = {}; + self.prompt([ + Input('outputPropTypes', 'write your values of these properties seperated by comma') + ]).then( (outputPropAnswer) => { + const outputAnswers = outputPropAnswer['outputPropTypes'].split(','); + for(let i = 0; i < answer.length; i++) { + webpackOutputPoint[answer[i]] = '\'' + outputAnswers[i] + '\''; + } + resolve(webpackOutputPoint); + }); + }); +}; diff --git a/lib/creator/yeoman/utils/plugins.js b/lib/creator/yeoman/utils/plugins.js new file mode 100644 index 00000000000..90b39179d41 --- /dev/null +++ b/lib/creator/yeoman/utils/plugins.js @@ -0,0 +1,5 @@ +module.exports = () => { + return [ + 'new UglifyJSPlugin()' + ]; +}; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 6a02f2fe713..b3855a78565 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -1,138 +1,92 @@ -/* eslint-disable quotes */ const Generator = require('yeoman-generator'); -const assetFilterFunction = require('webpack-addons').assetFilterFunction; -const externalRegExpFunction = require('webpack-addons').externalRegExpFunction; -const parseValue = require('webpack-addons').parseValue; + +const commonChunksPluginCreate = require('webpack-addons').commonChunksPluginCreate; + +const Input = require('webpack-addons').Input; +const RawList = require('webpack-addons').RawList; +const CheckList = require('webpack-addons').CheckList; + +const entryQuestions = require('./utils/entry'); +const OutputQuestions = require('./utils/output'); +const getDefaultLoaders = require('./utils/module'); +const getDefaultPlugins = require('./utils/plugins'); module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { super(args, opts); this.configuration = { - dev: { + config: { webpackOptions: {}, topScope: [] } }; } prompting() { - this.configuration.dev.webpackOptions.entry = { - vendor: 'home', - js: 'yes', - ohye: 'no' - }; - this.configuration.dev.webpackOptions.output = {}; - this.configuration.dev.webpackOptions.output.filename = "'hello'"; - this.configuration.dev.webpackOptions.output.path = 'path.join(__dirname, "somepath")'; - this.configuration.dev.webpackOptions.output.pathinfo = true; - this.configuration.dev.webpackOptions.output.publicPath = "'https://newbie.com'"; - this.configuration.dev.webpackOptions.output.sourceMapFilename = "'[name].map'"; - /* eslint-disable */ - this.configuration.dev.webpackOptions.output.sourcePrefix = parseValue("'\t'") - /* esline-enable */ - this.configuration.dev.webpackOptions.output.umdNamedDefine = true; - this.configuration.dev.webpackOptions.output.strictModuleExceptionHandling = true; - this.configuration.dev.webpackOptions.context = 'path.resolve(__dirname, "app")' - this.configuration.dev.webpackOptions.resolve = {}; - this.configuration.dev.webpackOptions.resolve.alias = {}; - this.configuration.dev.webpackOptions.resolve.alias.hello = '\':)\'' - this.configuration.dev.webpackOptions.resolve.aliasFields = ["'browser'"] - this.configuration.dev.webpackOptions.resolve.descriptionFiles = ["'a'", "'b'"] - this.configuration.dev.webpackOptions.resolve.enforceExtension = false - this.configuration.dev.webpackOptions.resolve.enforceModuleExtension = false - this.configuration.dev.webpackOptions.resolve.extensions = ["'hey'", "'gi'"] - this.configuration.dev.webpackOptions.resolve.mainFields = ["'mod'", "'ho'", "'bo'"] - this.configuration.dev.webpackOptions.resolve.mainFiles = ["'index'"] - this.configuration.dev.webpackOptions.resolve.modules = ["'Heo'"] - this.configuration.dev.webpackOptions.resolve.unsafeCache = true; - this.configuration.dev.webpackOptions.resolve.plugins = [ - "new webpack.optimize.CommonsChunkPlugin({name:" + "'" + 'vendor' + "'" + ",filename:" + "'" + 'vendor' + "-[hash].min.js'})" - ]; - this.configuration.dev.webpackOptions.resolve.symlinks = true; - this.configuration.dev.webpackOptions.resolve.cachePredicate = "function()" + "{\n return " + "true" + "\n}"; - this.configuration.dev.webpackOptions.devtool = 'eval' - this.configuration.dev.webpackOptions.target = 'async-node' - this.configuration.dev.webpackOptions.watch = true; - this.configuration.dev.webpackOptions.watchOptions = { - aggregateTimeout: 300, - poll: 1000, - ignored: '/node_modules/' - } - this.configuration.dev.webpackOptions.externals = { - jquery: 'jQuery', - subtract: 'tracty', - lodash : { - commonjs: 'lodash', - amd: 'lodash', - root: '_' // indicates global variable - } - } - this.configuration.dev.webpackOptions.externals = [ - externalRegExpFunction('^.js$') - ] - this.configuration.dev.webpackOptions.externals = /^(jquery|\$)$/i - this.configuration.dev.webpackOptions.node = { - console: false, - global: true, - process: true, - Buffer: true, - __filename: 'mock', - __dirname: 'mock', - setImmediate: true - } - this.configuration.dev.webpackOptions.performance = { - hints: "'warning'", - maxEntrypointSize: 400000, - maxAssetSize: 100000, - assetFilter: assetFilterFunction('js') - } - this.configuration.dev.webpackOptions.stats = 'errors-only' - this.configuration.dev.webpackOptions.amd = { - jQuery: true, - kQuery: false - } - this.configuration.dev.webpackOptions.bail = true; - this.configuration.dev.webpackOptions.cache = 'myCache' - this.configuration.dev.webpackOptions.profile = true - this.configuration.dev.webpackOptions.module = { - noParse: new RegExp(/jquery|lodash/), - rules: [ - { - test: new RegExp('/\.jsx?$/'), - include: [ - /* eslint-disable */ - 'path.resolve(__dirname, "app")' - /* eslint-enable */ - ], - exclude: [ - /* eslint-disable */ - 'path.resolve(__dirname, ".." , "app", "demo-files")' - /* eslint-enable */ - ], - enforce: "'pre'", - loader: "'babel-loader'", - options: { - presets: ['es2015'] - }, - }, - { - test: new RegExp('\\.html$'), - use: [ - "'htmllint-loader'", - { - loader: "'html-loader'", - options: { - hello: "'world'" + let done = this.async(); + let self = this; + + this.configuration.config.webpackOptions.module = getDefaultLoaders(); + this.configuration.config.webpackOptions.plugins = getDefaultPlugins(); + this.prompt([ + RawList('entryType', 'What kind of entry point do you want?', ['Array', 'Function', 'String', 'Object']) + ]).then( (entryTypeAnswer) => { + // Ask different questions for entry points + entryQuestions(self, entryTypeAnswer).then(entryOptions => { + this.configuration.config.webpackOptions.entry = entryOptions; + }).then( () => { + + this.prompt([ + CheckList('outputType', 'What kind of output properties do you want?', [ + 'chunkFilename', + 'filename', + 'path' + ]) + ]).then( (outputTypeAnswer) => { + // Ask different questions to output + OutputQuestions(self, outputTypeAnswer['outputType']).then(outputOptions => { + this.configuration.config.webpackOptions.output = outputOptions; + }).then( () => { + // Ask if the user wants to use extractPlugin + this.prompt([ + Input('extractPlugin', 'If you got a css file, what\'s it named?') + ]).then( (extractAnswer) => { + if(extractAnswer['extractPlugin'].length !== 0) { + this.configuration.config.webpackOptions.plugins.push( + 'new ExtractTextPlugin(\'styles.css\')' + ); + this.configuration.config.webpackOptions.module.rules.push({ + test: new RegExp(/\.css$/), + use: `ExtractTextPlugin.extract({ + fallback: 'style-loader', + use: 'css-loader' + })` + }); + this.configuration.config.topScope.push( + 'const ExtractTextPlugin = require(\'extract-text-webpack-plugin\');' + ); } - } - ] - }, - ], - } - this.configuration.dev.webpackOptions.plugins = [ - "new webpack.optimize.CommonsChunkPlugin({name:" + "'" + 'vendor' + "'" + ",filename:" + "'" + 'vendor' + "-[hash].min.js'})" - ] - this.configuration.dev.topScope = ['const path = require("path");', 'const webpack = require("webpack");', 'const myCache = {};'] - this.configuration.dev.configName = 'dev'; + }).then( () => { + // Ask if the user wants to use code splitting + this.prompt([ + Input('CommonsChunkPlugin', 'If want to use split one entry point, what is it named?') + ]).then( (CommonsChunkPluginAnswer) => { + if(CommonsChunkPluginAnswer['CommonsChunkPlugin'].length !== 0) { + this.configuration.config.webpackOptions.plugins.push( + commonChunksPluginCreate(CommonsChunkPluginAnswer['CommonsChunkPlugin']) + ); + } + }).then( () => { + this.configuration.config.topScope.push( + 'const UglifyJSPlugin = require(\'uglifyjs-webpack-plugin\');', + '\n' + ); + done(); + }); + }); + }); + }); + }); + }); } }; diff --git a/lib/utils/resolve-packages.js b/lib/utils/resolve-packages.js index 52f3b3e7db0..eb960e2a4cc 100644 --- a/lib/utils/resolve-packages.js +++ b/lib/utils/resolve-packages.js @@ -67,13 +67,13 @@ module.exports = function resolvePackages(pkg) { console.log('Submit an issue for', pkg, 'if this persists'); console.log('\nReason: \n'); console.error(chalk.bold.red(err)); - process.exit(1); + process.exitCode = 1; } }).catch(err => { console.log('Package Coudln\'t be installed, aborting..'); console.log('\nReason: \n'); console.error(chalk.bold.red(err)); - process.exit(1); + process.exitCode = 1; }).then( () => { if(packageLocations.length === pkg.length) return creator(packageLocations); }); From f33f521d803ea2f9eb1c0358e668aef1b7297879 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Tue, 2 May 2017 20:17:18 +0200 Subject: [PATCH 085/101] chore: update addons pkg and reformat extractAnswer --- lib/creator/yeoman/utils/entry.js | 2 +- lib/creator/yeoman/utils/output.js | 2 +- lib/creator/yeoman/webpack-generator.js | 6 +++--- package.json | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 79c9d29c2d2..52715c63eb5 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -1,7 +1,7 @@ const Input = require('webpack-addons').Input; module.exports = (self, answer) => { - return new Promise( (resolve, reject) => { + return new Promise( (resolve) => { let webpackEntryPoint; let entryIdentifiers; diff --git a/lib/creator/yeoman/utils/output.js b/lib/creator/yeoman/utils/output.js index 86e5608e445..e0f2e87056e 100644 --- a/lib/creator/yeoman/utils/output.js +++ b/lib/creator/yeoman/utils/output.js @@ -1,7 +1,7 @@ const Input = require('webpack-addons').Input; module.exports = (self, answer) => { - return new Promise( (resolve, reject) => { + return new Promise( (resolve) => { let webpackOutputPoint = {}; self.prompt([ Input('outputPropTypes', 'write your values of these properties seperated by comma') diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index b3855a78565..1734aea78ad 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -1,6 +1,6 @@ const Generator = require('yeoman-generator'); -const commonChunksPluginCreate = require('webpack-addons').commonChunksPluginCreate; +const createCommonsChunkPlugin = require('webpack-addons').createCommonsChunkPlugin; const Input = require('webpack-addons').Input; const RawList = require('webpack-addons').RawList; @@ -52,7 +52,7 @@ module.exports = class WebpackGenerator extends Generator { ]).then( (extractAnswer) => { if(extractAnswer['extractPlugin'].length !== 0) { this.configuration.config.webpackOptions.plugins.push( - 'new ExtractTextPlugin(\'styles.css\')' + 'new ExtractTextPlugin(\'' + extractAnswer['extractPlugin'] + '\')' ); this.configuration.config.webpackOptions.module.rules.push({ test: new RegExp(/\.css$/), @@ -72,7 +72,7 @@ module.exports = class WebpackGenerator extends Generator { ]).then( (CommonsChunkPluginAnswer) => { if(CommonsChunkPluginAnswer['CommonsChunkPlugin'].length !== 0) { this.configuration.config.webpackOptions.plugins.push( - commonChunksPluginCreate(CommonsChunkPluginAnswer['CommonsChunkPlugin']) + createCommonsChunkPlugin(CommonsChunkPluginAnswer['CommonsChunkPlugin']) ); } }).then( () => { diff --git a/package.json b/package.json index b79272aa1f2..a18189907ef 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "recast": "git://github.com/kalcifer/recast.git#bug/allowbreak", "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", - "webpack-addons": "^1.0.5", + "webpack-addons": "^1.1.0", "yargs": "^6.5.0", "yeoman-environment": "^1.6.6", "yeoman-generator": "git://github.com/ev1stensberg/generator.git#Feature-getArgument" From d1342ed39fbc14e02bab86882c6c8c781184a4bc Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Thu, 4 May 2017 22:24:10 +0200 Subject: [PATCH 086/101] enhancements: better bin resolves & default generator Thanks to Sindre Sorhus & Addy Osmani for the review. Fixed some better resolves in bin folder, removed some code in default generator to better scaffold for beginners. --- bin/webpack.js | 23 +++--- lib/creator/index.js | 2 +- lib/creator/yeoman/utils/entry.js | 36 ++++------ lib/creator/yeoman/utils/output.js | 16 ----- lib/creator/yeoman/webpack-generator.js | 93 +++++++++++++------------ package.json | 1 + 6 files changed, 76 insertions(+), 95 deletions(-) delete mode 100644 lib/creator/yeoman/utils/output.js diff --git a/bin/webpack.js b/bin/webpack.js index 6ba04c67ee9..6cc71f70226 100755 --- a/bin/webpack.js +++ b/bin/webpack.js @@ -1,17 +1,24 @@ +#!/usr/bin/env node /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var path = require('path'); +var resolveCwd = require('resolve-cwd'); + +var localCLI = resolveCwd.silent('webpack-cli/bin/webpack'); + +if (localCLI && path.relative(localCLI, __filename) !== '') { + require(localCLI); +} else { + try { + require('./webpack'); + } catch (err) { + console.error(`\n ${err.message}`); + process.exitCode = 1; + } +} -// Local version replace global one -try { - var localWebpack = require.resolve(path.join(process.cwd(), 'node_modules', - 'webpack', 'node_modules', 'webpack-cli', 'bin', 'webpack.js')); - if(__filename !== localWebpack) { - return require(localWebpack); - } //eslint-disable-next-line -} catch(e) {} var yargs = require('yargs') .usage('webpack ' + require('../package.json').version + '\n' + 'Usage: https://webpack.js.org/api/cli/\n' + diff --git a/lib/creator/index.js b/lib/creator/index.js index cd3174edf14..12ec46c8fc8 100644 --- a/lib/creator/index.js +++ b/lib/creator/index.js @@ -54,7 +54,7 @@ function creator(options) { function replaceGeneratorName(name) { return name.replace( - /(webpack-addons)?([^:]+)(:.*)?/g, 'generator$2'); + /(webpack-addons)?([^:]+)(:.*)?/g, 'generator$2'); } module.exports = { diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 52715c63eb5..2d5fbed344d 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -6,29 +6,22 @@ module.exports = (self, answer) => { let entryIdentifiers; let entryProperties; - if(answer['entryType'].indexOf('Array') >= 0) { + if(answer['entryType'] == 'Multiple') { self.prompt([ - Input('arrayNumber', 'write your entry points seperated by comma') - ]).then( (arrayAnswer) => { - webpackEntryPoint = arrayAnswer['arrayNumber'].split(','); - resolve(webpackEntryPoint.map( (prop) => { - let newProp = `'${prop}'`; - return newProp; - })); - }); - } - else if(answer['entryType'].indexOf('Object') >= 0) { - self.prompt([ - Input('objectNames', 'List your entry properties seperated by comma') - ]).then( (objectIdentifierAnswer) => { + Input('multipleEntries', 'Write the name you want for your modules seperated by comma') + ]).then( (multipleEntriesAnswer) => { webpackEntryPoint = {}; - entryIdentifiers = objectIdentifierAnswer['objectNames'].split(','); + entryIdentifiers = multipleEntriesAnswer['multipleEntries'].split(','); self.prompt([ - Input('objectProperties', 'List your entry properties seperated by comma') + Input('objectProperties', 'Write the location of those modules seperated by comma') ]).then( (objectPropAnswer) => { entryProperties = objectPropAnswer['objectProperties'].split(','); for(let k = 0; k < entryIdentifiers.length; k++) { - webpackEntryPoint[entryIdentifiers[k]] = `'${entryProperties[k]}'`; + if(entryProperties[k].charAt(0) == '(' || entryProperties[k].charAt(0) == '[') { + webpackEntryPoint[entryIdentifiers[k]] = entryProperties[k]; + } else { + webpackEntryPoint[entryIdentifiers[k]] = `'${entryProperties[k]}.js'`; + } } resolve(webpackEntryPoint); }); @@ -36,14 +29,9 @@ module.exports = (self, answer) => { } else { self.prompt([ - Input('singularEntry', 'What\'s your entry point?') + Input('singularEntry', 'Write the location of module you would like to use') ]).then( (singularAnswer) => { - if(answer['entryType'].indexOf('String') >= 0) { - webpackEntryPoint = `'${singularAnswer['singularEntry']}'`; - } else { - webpackEntryPoint = singularAnswer['singularEntry']; - } - resolve(webpackEntryPoint); + resolve(`'${singularAnswer['singularEntry']}.js'`); }); } }); diff --git a/lib/creator/yeoman/utils/output.js b/lib/creator/yeoman/utils/output.js deleted file mode 100644 index e0f2e87056e..00000000000 --- a/lib/creator/yeoman/utils/output.js +++ /dev/null @@ -1,16 +0,0 @@ -const Input = require('webpack-addons').Input; - -module.exports = (self, answer) => { - return new Promise( (resolve) => { - let webpackOutputPoint = {}; - self.prompt([ - Input('outputPropTypes', 'write your values of these properties seperated by comma') - ]).then( (outputPropAnswer) => { - const outputAnswers = outputPropAnswer['outputPropTypes'].split(','); - for(let i = 0; i < answer.length; i++) { - webpackOutputPoint[answer[i]] = '\'' + outputAnswers[i] + '\''; - } - resolve(webpackOutputPoint); - }); - }); -}; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 1734aea78ad..ae6e17e3598 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -4,10 +4,8 @@ const createCommonsChunkPlugin = require('webpack-addons').createCommonsChunkPlu const Input = require('webpack-addons').Input; const RawList = require('webpack-addons').RawList; -const CheckList = require('webpack-addons').CheckList; const entryQuestions = require('./utils/entry'); -const OutputQuestions = require('./utils/output'); const getDefaultLoaders = require('./utils/module'); const getDefaultPlugins = require('./utils/plugins'); @@ -24,65 +22,68 @@ module.exports = class WebpackGenerator extends Generator { prompting() { let done = this.async(); let self = this; - + let oneOrMoreEntries; this.configuration.config.webpackOptions.module = getDefaultLoaders(); this.configuration.config.webpackOptions.plugins = getDefaultPlugins(); this.prompt([ - RawList('entryType', 'What kind of entry point do you want?', ['Array', 'Function', 'String', 'Object']) + RawList('entryType', 'Would you like to bundle a single or multiple javascript modules?', + ['Single', 'Multiple']) ]).then( (entryTypeAnswer) => { // Ask different questions for entry points entryQuestions(self, entryTypeAnswer).then(entryOptions => { this.configuration.config.webpackOptions.entry = entryOptions; + oneOrMoreEntries = Object.keys(entryOptions); }).then( () => { this.prompt([ - CheckList('outputType', 'What kind of output properties do you want?', [ - 'chunkFilename', - 'filename', - 'path' - ]) + Input('outputType', 'What folder do you want to put those files in?') ]).then( (outputTypeAnswer) => { - // Ask different questions to output - OutputQuestions(self, outputTypeAnswer['outputType']).then(outputOptions => { - this.configuration.config.webpackOptions.output = outputOptions; - }).then( () => { + if(!this.configuration.config.webpackOptions.entry.length) { + this.configuration.config.webpackOptions.output = { + filename: '\'[name]-[chunkhash].js\'', + chunkFilename: '\'[chunkhash].js\'' + }; + } else { + this.configuration.config.webpackOptions.output = { + filename: '\'[name].bundle.js\'', + }; + } + if(outputTypeAnswer['outputType'].length) { + this.configuration.config.webpackOptions.output.path = `'${outputTypeAnswer['outputType']}'`; + } + }).then( () => { // Ask if the user wants to use extractPlugin - this.prompt([ - Input('extractPlugin', 'If you got a css file, what\'s it named?') - ]).then( (extractAnswer) => { - if(extractAnswer['extractPlugin'].length !== 0) { + this.prompt([ + Input('extractPlugin', 'What\'s the name of your css file? (press enter to skip)') + ]).then( (extractAnswer) => { + if(extractAnswer['extractPlugin'].length !== 0) { + this.configuration.config.webpackOptions.plugins.push( + 'new ExtractTextPlugin(\'' + extractAnswer['extractPlugin'] + '.css\')' + ); + this.configuration.config.webpackOptions.module.rules.push({ + test: new RegExp(/\.css$/), + use: `ExtractTextPlugin.extract({ + fallback: 'style-loader', + use: 'css-loader' + })` + }); + this.configuration.config.topScope.push( + 'const ExtractTextPlugin = require(\'extract-text-webpack-plugin\');' + ); + } + }).then( () => { + if(!this.configuration.config.webpackOptions.entry.length) { + oneOrMoreEntries.forEach( (prop) => { this.configuration.config.webpackOptions.plugins.push( - 'new ExtractTextPlugin(\'' + extractAnswer['extractPlugin'] + '\')' - ); - this.configuration.config.webpackOptions.module.rules.push({ - test: new RegExp(/\.css$/), - use: `ExtractTextPlugin.extract({ - fallback: 'style-loader', - use: 'css-loader' - })` - }); - this.configuration.config.topScope.push( - 'const ExtractTextPlugin = require(\'extract-text-webpack-plugin\');' - ); - } - }).then( () => { - // Ask if the user wants to use code splitting - this.prompt([ - Input('CommonsChunkPlugin', 'If want to use split one entry point, what is it named?') - ]).then( (CommonsChunkPluginAnswer) => { - if(CommonsChunkPluginAnswer['CommonsChunkPlugin'].length !== 0) { - this.configuration.config.webpackOptions.plugins.push( - createCommonsChunkPlugin(CommonsChunkPluginAnswer['CommonsChunkPlugin']) - ); - } - }).then( () => { - this.configuration.config.topScope.push( - 'const UglifyJSPlugin = require(\'uglifyjs-webpack-plugin\');', - '\n' + createCommonsChunkPlugin(prop) ); - done(); }); - }); + } + this.configuration.config.topScope.push( + 'const UglifyJSPlugin = require(\'uglifyjs-webpack-plugin\');', + '\n' + ); + done(); }); }); }); diff --git a/package.json b/package.json index a18189907ef..cf93f7ab0cb 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,7 @@ "p-lazy": "^1.0.0", "prettier": "^1.2.2", "recast": "git://github.com/kalcifer/recast.git#bug/allowbreak", + "resolve-cwd": "^2.0.0", "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", "webpack-addons": "^1.1.0", From 21e78581ed2b9e4115302e5857123318d0680f97 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Thu, 4 May 2017 22:47:15 +0200 Subject: [PATCH 087/101] enhancements: use validation to force answers --- lib/creator/yeoman/utils/entry.js | 21 +++++++++++++++++---- lib/creator/yeoman/utils/validate.js | 7 +++++++ lib/creator/yeoman/webpack-generator.js | 8 ++++---- package.json | 2 +- 4 files changed, 29 insertions(+), 9 deletions(-) create mode 100644 lib/creator/yeoman/utils/validate.js diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 2d5fbed344d..93f53d47dc7 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -1,4 +1,5 @@ -const Input = require('webpack-addons').Input; +const InputValidate = require('webpack-addons').InputValidate; +const validate = require('./validate'); module.exports = (self, answer) => { return new Promise( (resolve) => { @@ -8,12 +9,20 @@ module.exports = (self, answer) => { let entryProperties; if(answer['entryType'] == 'Multiple') { self.prompt([ - Input('multipleEntries', 'Write the name you want for your modules seperated by comma') + InputValidate( + 'multipleEntries', + 'Write the name you want for your modules seperated by comma', + validate + ) ]).then( (multipleEntriesAnswer) => { webpackEntryPoint = {}; entryIdentifiers = multipleEntriesAnswer['multipleEntries'].split(','); self.prompt([ - Input('objectProperties', 'Write the location of those modules seperated by comma') + InputValidate( + 'objectProperties', + 'Write the location of those modules seperated by comma', + validate + ) ]).then( (objectPropAnswer) => { entryProperties = objectPropAnswer['objectProperties'].split(','); for(let k = 0; k < entryIdentifiers.length; k++) { @@ -29,7 +38,11 @@ module.exports = (self, answer) => { } else { self.prompt([ - Input('singularEntry', 'Write the location of module you would like to use') + InputValidate( + 'singularEntry', + 'Write the location of module you would like to use', + validate + ) ]).then( (singularAnswer) => { resolve(`'${singularAnswer['singularEntry']}.js'`); }); diff --git a/lib/creator/yeoman/utils/validate.js b/lib/creator/yeoman/utils/validate.js new file mode 100644 index 00000000000..bf981fd454f --- /dev/null +++ b/lib/creator/yeoman/utils/validate.js @@ -0,0 +1,7 @@ +module.exports = (value) => { + const pass = value.length; + if(pass) { + return true; + } + return 'Please specify an answer!'; +}; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index ae6e17e3598..1b8e890231b 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -3,11 +3,13 @@ const Generator = require('yeoman-generator'); const createCommonsChunkPlugin = require('webpack-addons').createCommonsChunkPlugin; const Input = require('webpack-addons').Input; +const InputValidate = require('webpack-addons').InputValidate; const RawList = require('webpack-addons').RawList; const entryQuestions = require('./utils/entry'); const getDefaultLoaders = require('./utils/module'); const getDefaultPlugins = require('./utils/plugins'); +const validate = require('./utils/validate'); module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { @@ -36,7 +38,7 @@ module.exports = class WebpackGenerator extends Generator { }).then( () => { this.prompt([ - Input('outputType', 'What folder do you want to put those files in?') + InputValidate('outputType', 'What folder do you want to put those files in?', validate) ]).then( (outputTypeAnswer) => { if(!this.configuration.config.webpackOptions.entry.length) { this.configuration.config.webpackOptions.output = { @@ -48,9 +50,7 @@ module.exports = class WebpackGenerator extends Generator { filename: '\'[name].bundle.js\'', }; } - if(outputTypeAnswer['outputType'].length) { - this.configuration.config.webpackOptions.output.path = `'${outputTypeAnswer['outputType']}'`; - } + this.configuration.config.webpackOptions.output.path = `'${outputTypeAnswer['outputType']}'`; }).then( () => { // Ask if the user wants to use extractPlugin this.prompt([ diff --git a/package.json b/package.json index cf93f7ab0cb..39ef6175b9d 100644 --- a/package.json +++ b/package.json @@ -49,7 +49,7 @@ "resolve-cwd": "^2.0.0", "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", - "webpack-addons": "^1.1.0", + "webpack-addons": "^1.1.1", "yargs": "^6.5.0", "yeoman-environment": "^1.6.6", "yeoman-generator": "git://github.com/ev1stensberg/generator.git#Feature-getArgument" From 0344e6a12a66be765a8f7971075fb1e289ba1405 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Thu, 4 May 2017 22:52:38 +0200 Subject: [PATCH 088/101] enhancements: check identifiers with properties --- lib/creator/yeoman/utils/entry.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 93f53d47dc7..13bfecb8f54 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -2,11 +2,24 @@ const InputValidate = require('webpack-addons').InputValidate; const validate = require('./validate'); module.exports = (self, answer) => { + let entryIdentifiers; + let entryProperties; + + const validateProperties = (value) => { + const valLength = value.length; + const values = value.split(','); + if(!valLength) { + return 'Please specify an answer!'; + } + else if(valLength && values.length == entryIdentifiers.length) { + return true; + } else { + return 'You forgot to add one or more property to your entry point!'; + } + }; return new Promise( (resolve) => { let webpackEntryPoint; - let entryIdentifiers; - let entryProperties; if(answer['entryType'] == 'Multiple') { self.prompt([ InputValidate( @@ -21,7 +34,7 @@ module.exports = (self, answer) => { InputValidate( 'objectProperties', 'Write the location of those modules seperated by comma', - validate + validateProperties ) ]).then( (objectPropAnswer) => { entryProperties = objectPropAnswer['objectProperties'].split(','); From 663133aac9b96fa5313662ddbbcc90c035ff84c4 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Thu, 4 May 2017 23:05:30 +0200 Subject: [PATCH 089/101] enhancements: revise anti pattern for promise MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks to Sindre Sørhus for this fix. Object references are now making sure our callbacks are held, and removed the return of the promise and rather used the object we want to return. --- lib/creator/yeoman/utils/entry.js | 77 +++++++++++++++---------------- 1 file changed, 38 insertions(+), 39 deletions(-) diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 13bfecb8f54..517f4741e88 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -2,9 +2,12 @@ const InputValidate = require('webpack-addons').InputValidate; const validate = require('./validate'); module.exports = (self, answer) => { + let webpackEntryPoint; let entryIdentifiers; let entryProperties; + let result; + const validateProperties = (value) => { const valLength = value.length; const values = value.split(','); @@ -17,48 +20,44 @@ module.exports = (self, answer) => { return 'You forgot to add one or more property to your entry point!'; } }; - return new Promise( (resolve) => { - let webpackEntryPoint; - if(answer['entryType'] == 'Multiple') { - self.prompt([ + if(answer['entryType'] == 'Multiple') { + result = self.prompt([ + InputValidate( + 'multipleEntries', + 'Write the name you want for your modules seperated by comma', + validate + ) + ]).then( (multipleEntriesAnswer) => { + webpackEntryPoint = {}; + entryIdentifiers = multipleEntriesAnswer['multipleEntries'].split(','); + return self.prompt([ InputValidate( - 'multipleEntries', - 'Write the name you want for your modules seperated by comma', - validate + 'objectProperties', + 'Write the location of those modules seperated by comma', + validateProperties ) - ]).then( (multipleEntriesAnswer) => { - webpackEntryPoint = {}; - entryIdentifiers = multipleEntriesAnswer['multipleEntries'].split(','); - self.prompt([ - InputValidate( - 'objectProperties', - 'Write the location of those modules seperated by comma', - validateProperties - ) - ]).then( (objectPropAnswer) => { - entryProperties = objectPropAnswer['objectProperties'].split(','); - for(let k = 0; k < entryIdentifiers.length; k++) { - if(entryProperties[k].charAt(0) == '(' || entryProperties[k].charAt(0) == '[') { - webpackEntryPoint[entryIdentifiers[k]] = entryProperties[k]; - } else { - webpackEntryPoint[entryIdentifiers[k]] = `'${entryProperties[k]}.js'`; - } + ]).then( (objectPropAnswer) => { + entryProperties = objectPropAnswer['objectProperties'].split(','); + for(let k = 0; k < entryIdentifiers.length; k++) { + if(entryProperties[k].charAt(0) == '(' || entryProperties[k].charAt(0) == '[') { + webpackEntryPoint[entryIdentifiers[k]] = entryProperties[k]; + } else { + webpackEntryPoint[entryIdentifiers[k]] = `'${entryProperties[k]}.js'`; } - resolve(webpackEntryPoint); - }); - }); - } - else { - self.prompt([ - InputValidate( - 'singularEntry', - 'Write the location of module you would like to use', - validate - ) - ]).then( (singularAnswer) => { - resolve(`'${singularAnswer['singularEntry']}.js'`); + return webpackEntryPoint; + } }); - } - }); + }); + } + else { + result = self.prompt([ + InputValidate( + 'singularEntry', + 'Write the location of module you would like to use', + validate + ) + ]).then( (singularAnswer) => `'${singularAnswer['singularEntry']}.js'`); + } + return result; }; From 907a1f76070352beca32dc96780de1eb0fa88a15 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 5 May 2017 14:45:26 +0200 Subject: [PATCH 090/101] enhancements: rename write to type and split params to newline --- lib/creator/yeoman/utils/entry.js | 8 ++++---- lib/creator/yeoman/webpack-generator.js | 18 ++++++++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 517f4741e88..cc957837a91 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -21,11 +21,11 @@ module.exports = (self, answer) => { } }; - if(answer['entryType'] == 'Multiple') { + if(answer['entryType'] === 'Multiple') { result = self.prompt([ InputValidate( 'multipleEntries', - 'Write the name you want for your modules seperated by comma', + 'Type the name you want for your modules seperated by comma', validate ) ]).then( (multipleEntriesAnswer) => { @@ -34,7 +34,7 @@ module.exports = (self, answer) => { return self.prompt([ InputValidate( 'objectProperties', - 'Write the location of those modules seperated by comma', + 'Type the location of those modules seperated by comma', validateProperties ) ]).then( (objectPropAnswer) => { @@ -54,7 +54,7 @@ module.exports = (self, answer) => { result = self.prompt([ InputValidate( 'singularEntry', - 'Write the location of module you would like to use', + 'Type the location of module you would like to use', validate ) ]).then( (singularAnswer) => `'${singularAnswer['singularEntry']}.js'`); diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 1b8e890231b..b09ba2c83ed 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -28,8 +28,11 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.config.webpackOptions.module = getDefaultLoaders(); this.configuration.config.webpackOptions.plugins = getDefaultPlugins(); this.prompt([ - RawList('entryType', 'Would you like to bundle a single or multiple javascript modules?', - ['Single', 'Multiple']) + RawList( + 'entryType', + 'Would you like to bundle a single or multiple javascript modules?', + ['Single', 'Multiple'] + ) ]).then( (entryTypeAnswer) => { // Ask different questions for entry points entryQuestions(self, entryTypeAnswer).then(entryOptions => { @@ -38,7 +41,11 @@ module.exports = class WebpackGenerator extends Generator { }).then( () => { this.prompt([ - InputValidate('outputType', 'What folder do you want to put those files in?', validate) + InputValidate( + 'outputType', + 'What folder do you want to put those files in?', + validate + ) ]).then( (outputTypeAnswer) => { if(!this.configuration.config.webpackOptions.entry.length) { this.configuration.config.webpackOptions.output = { @@ -54,7 +61,10 @@ module.exports = class WebpackGenerator extends Generator { }).then( () => { // Ask if the user wants to use extractPlugin this.prompt([ - Input('extractPlugin', 'What\'s the name of your css file? (press enter to skip)') + Input( + 'extractPlugin', + 'What\'s the name of your css file? (press enter to skip)' + ) ]).then( (extractAnswer) => { if(extractAnswer['extractPlugin'].length !== 0) { this.configuration.config.webpackOptions.plugins.push( From c58f79331ab88bfddb78bb9e4a43da316c252eb4 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Fri, 5 May 2017 18:30:11 +0200 Subject: [PATCH 091/101] enhancements: add better scaffold to generator --- lib/creator/yeoman/utils/entry.js | 51 +++++++++---------------- lib/creator/yeoman/utils/tooltip.js | 32 ++++++++++++++++ lib/creator/yeoman/webpack-generator.js | 16 ++++++++ 3 files changed, 67 insertions(+), 32 deletions(-) create mode 100644 lib/creator/yeoman/utils/tooltip.js diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index cc957837a91..92052c2bc80 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -2,25 +2,9 @@ const InputValidate = require('webpack-addons').InputValidate; const validate = require('./validate'); module.exports = (self, answer) => { - let webpackEntryPoint; let entryIdentifiers; - let entryProperties; - let result; - const validateProperties = (value) => { - const valLength = value.length; - const values = value.split(','); - if(!valLength) { - return 'Please specify an answer!'; - } - else if(valLength && values.length == entryIdentifiers.length) { - return true; - } else { - return 'You forgot to add one or more property to your entry point!'; - } - }; - if(answer['entryType'] === 'Multiple') { result = self.prompt([ InputValidate( @@ -29,24 +13,27 @@ module.exports = (self, answer) => { validate ) ]).then( (multipleEntriesAnswer) => { - webpackEntryPoint = {}; + let webpackEntryPoint = {}; entryIdentifiers = multipleEntriesAnswer['multipleEntries'].split(','); - return self.prompt([ + function forEachPromise(obj, fn) { + return obj.reduce(function (promise, prop) { + const trimmedProp = prop.trim(); + return promise.then(function (n) { + webpackEntryPoint = Object.assign({}, n); + return fn(trimmedProp); + }); + }, Promise.resolve()); + } + return forEachPromise(entryIdentifiers, (entryProp) => self.prompt([ InputValidate( - 'objectProperties', - 'Type the location of those modules seperated by comma', - validateProperties + `${entryProp}`, + `What is the location of '${entryProp}'?`, + validate ) - ]).then( (objectPropAnswer) => { - entryProperties = objectPropAnswer['objectProperties'].split(','); - for(let k = 0; k < entryIdentifiers.length; k++) { - if(entryProperties[k].charAt(0) == '(' || entryProperties[k].charAt(0) == '[') { - webpackEntryPoint[entryIdentifiers[k]] = entryProperties[k]; - } else { - webpackEntryPoint[entryIdentifiers[k]] = `'${entryProperties[k]}.js'`; - } - return webpackEntryPoint; - } + ])).then(propAns => { + const prop = Object.keys(propAns); + webpackEntryPoint[prop] = propAns[prop]; + return webpackEntryPoint; }); }); } @@ -57,7 +44,7 @@ module.exports = (self, answer) => { 'Type the location of module you would like to use', validate ) - ]).then( (singularAnswer) => `'${singularAnswer['singularEntry']}.js'`); + ]).then( (singularAnswer) => singularAnswer['singularEntry']); } return result; }; diff --git a/lib/creator/yeoman/utils/tooltip.js b/lib/creator/yeoman/utils/tooltip.js new file mode 100644 index 00000000000..9d6d6c0d438 --- /dev/null +++ b/lib/creator/yeoman/utils/tooltip.js @@ -0,0 +1,32 @@ +module.exports = { + uglify: () => { + return (`/* + * We've enabled UglifyJSPlugin for you! This minifies your app + * in order to load faster and run less javascript. + * + * https://github.com/webpack-contrib/uglifyjs-webpack-plugin + * + */`); + }, + commonsChunk: () => { + return (`/* + * We've enabled commonsChunkPlugin for you. This allows your app to + * load faster and it splits the modules you provided as entries across + * different bundles! + * + * https://webpack.js.org/plugins/commons-chunk-plugin/ + * + */`); + }, + cssPlugin: () => { + return( + `/* + * We've enabled ExtractTextPlugin for you. This allows your app to + * use css modules that will be moved into a seperate CSS file instead of inside + * one of your module entries! + * + * https://github.com/webpack-contrib/extract-text-webpack-plugin + * + */`); + } +}; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index b09ba2c83ed..19fc15a976f 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -1,4 +1,5 @@ const Generator = require('yeoman-generator'); +const chalk = require('chalk'); const createCommonsChunkPlugin = require('webpack-addons').createCommonsChunkPlugin; @@ -9,6 +10,7 @@ const RawList = require('webpack-addons').RawList; const entryQuestions = require('./utils/entry'); const getDefaultLoaders = require('./utils/module'); const getDefaultPlugins = require('./utils/plugins'); +const tooltip = require('./utils/tooltip'); const validate = require('./utils/validate'); module.exports = class WebpackGenerator extends Generator { @@ -22,11 +24,15 @@ module.exports = class WebpackGenerator extends Generator { }; } prompting() { + + process.stdout.write(`\n${chalk.red.bold('Remember to add string quotes to your bundle entries and file extensions!')}\n\n`); + let done = this.async(); let self = this; let oneOrMoreEntries; this.configuration.config.webpackOptions.module = getDefaultLoaders(); this.configuration.config.webpackOptions.plugins = getDefaultPlugins(); + this.configuration.config.topScope.push(tooltip.uglify()); this.prompt([ RawList( 'entryType', @@ -48,6 +54,7 @@ module.exports = class WebpackGenerator extends Generator { ) ]).then( (outputTypeAnswer) => { if(!this.configuration.config.webpackOptions.entry.length) { + this.configuration.config.topScope.push(tooltip.commonsChunk()); this.configuration.config.webpackOptions.output = { filename: '\'[name]-[chunkhash].js\'', chunkFilename: '\'[chunkhash].js\'' @@ -67,6 +74,7 @@ module.exports = class WebpackGenerator extends Generator { ) ]).then( (extractAnswer) => { if(extractAnswer['extractPlugin'].length !== 0) { + this.configuration.config.topScope.push(tooltip.cssPlugin()); this.configuration.config.webpackOptions.plugins.push( 'new ExtractTextPlugin(\'' + extractAnswer['extractPlugin'] + '.css\')' ); @@ -99,5 +107,13 @@ module.exports = class WebpackGenerator extends Generator { }); }); } + installPlugins() { + this.npmInstall(['uglifyjs-webpack-plugin'], { 'save-dev': true }); + this.configuration.config.webpackOptions.plugins.forEach( (plugin) => { + if(plugin.indexOf('new ExtractTextPlugin') >= 0) { + this.npmInstall(['extract-text-webpack-plugin'], { 'save-dev': true }); + } + }); + } }; From 3e6115ac3289cfb72238a25042799c5981249385 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 6 May 2017 00:14:41 +0200 Subject: [PATCH 092/101] enhancements: make default generator more User Friendly --- lib/creator/yeoman/utils/entry.js | 37 +++++++++++++++++++++---- lib/creator/yeoman/webpack-generator.js | 7 ++--- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 92052c2bc80..730a3827462 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -5,7 +5,7 @@ module.exports = (self, answer) => { let entryIdentifiers; let result; - if(answer['entryType'] === 'Multiple') { + if(answer['entryType'] === 'Yes') { result = self.prompt([ InputValidate( 'multipleEntries', @@ -19,7 +19,22 @@ module.exports = (self, answer) => { return obj.reduce(function (promise, prop) { const trimmedProp = prop.trim(); return promise.then(function (n) { - webpackEntryPoint = Object.assign({}, n); + if(n) { + Object.keys(n).forEach( (val) => { + if( + n[val].charAt(0) !== '(' + && n[val].charAt(0) !== '[' + && n[val].indexOf('function') < 0 + && n[val].indexOf('path') < 0 + && n[val].indexOf('process') < 0 + ) { + n[val] = `'${n[val]}.js'`; + } + webpackEntryPoint[val] = n[val]; + }); + } else { + n = {}; + } return fn(trimmedProp); }); }, Promise.resolve()); @@ -31,8 +46,18 @@ module.exports = (self, answer) => { validate ) ])).then(propAns => { - const prop = Object.keys(propAns); - webpackEntryPoint[prop] = propAns[prop]; + Object.keys(propAns).forEach( (val) => { + if( + propAns[val].charAt(0) !== '(' + && propAns[val].charAt(0) !== '[' + && propAns[val].indexOf('function') < 0 + && propAns[val].indexOf('path') < 0 + && propAns[val].indexOf('process') < 0 + ) { + propAns[val] = `'${propAns[val]}.js'`; + } + webpackEntryPoint[val] = propAns[val]; + }); return webpackEntryPoint; }); }); @@ -41,10 +66,10 @@ module.exports = (self, answer) => { result = self.prompt([ InputValidate( 'singularEntry', - 'Type the location of module you would like to use', + 'Where is the bundle you want to use located?', validate ) - ]).then( (singularAnswer) => singularAnswer['singularEntry']); + ]).then( (singularAnswer) => `'${singularAnswer['singularEntry']}.js'`); } return result; }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 19fc15a976f..809a8eb8e16 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -25,19 +25,18 @@ module.exports = class WebpackGenerator extends Generator { } prompting() { - process.stdout.write(`\n${chalk.red.bold('Remember to add string quotes to your bundle entries and file extensions!')}\n\n`); - let done = this.async(); let self = this; let oneOrMoreEntries; + this.configuration.config.webpackOptions.module = getDefaultLoaders(); this.configuration.config.webpackOptions.plugins = getDefaultPlugins(); this.configuration.config.topScope.push(tooltip.uglify()); this.prompt([ RawList( 'entryType', - 'Would you like to bundle a single or multiple javascript modules?', - ['Single', 'Multiple'] + 'Will you be creating multiple bundles?', + ['Yes', 'No'] ) ]).then( (entryTypeAnswer) => { // Ask different questions for entry points From 0ba9d7d1130e2b4fa2d1e7e4b1d87c830a83d965 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sat, 6 May 2017 15:22:13 +0200 Subject: [PATCH 093/101] enhancements: ask if user wants to make the config at end --- lib/creator/yeoman/webpack-generator.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 809a8eb8e16..dd3841f7cf0 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -107,12 +107,29 @@ module.exports = class WebpackGenerator extends Generator { }); } installPlugins() { + let asyncDone = this.async(); this.npmInstall(['uglifyjs-webpack-plugin'], { 'save-dev': true }); this.configuration.config.webpackOptions.plugins.forEach( (plugin) => { if(plugin.indexOf('new ExtractTextPlugin') >= 0) { this.npmInstall(['extract-text-webpack-plugin'], { 'save-dev': true }); } }); + this.prompt([ + RawList( + 'finish', + 'Everything is set! Do you want to create your webpack.config.js?', + ['Yes', 'No'] + ) + ]).then( (answer) => { + if(answer['finish'] === 'Yes') { + asyncDone(); + } else { + process.stdout.write( + chalk.bold.red('\nInitializing aborted, run \'webpack init\' again if this was not intended.\n') + ); + process.exitCode = 0; + } + }); } }; From c6bd40c3303ca4faec97b79a59ff09c8023040b9 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 7 May 2017 12:36:10 +0200 Subject: [PATCH 094/101] enhancements: make default generator better --- lib/creator/yeoman/utils/entry.js | 3 +- lib/creator/yeoman/utils/module.js | 20 ++--- lib/creator/yeoman/webpack-generator.js | 114 +++++++++++------------- package.json | 2 +- 4 files changed, 60 insertions(+), 79 deletions(-) diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 730a3827462..8fde05ed914 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -4,8 +4,7 @@ const validate = require('./validate'); module.exports = (self, answer) => { let entryIdentifiers; let result; - - if(answer['entryType'] === 'Yes') { + if(answer['entryType'] === true) { result = self.prompt([ InputValidate( 'multipleEntries', diff --git a/lib/creator/yeoman/utils/module.js b/lib/creator/yeoman/utils/module.js index 5949599e56a..161ec111962 100644 --- a/lib/creator/yeoman/utils/module.js +++ b/lib/creator/yeoman/utils/module.js @@ -1,16 +1,12 @@ module.exports = () => { return { - rules: [ - { - test: new RegExp(/\.js$/), - exclude: '/node_modules/', - loader: '\'babel-loader\'', - options: { - presets: [ - '\'es2015\'' - ] - } - } - ] + test: new RegExp(/\.js$/), + exclude: '/node_modules/', + loader: '\'babel-loader\'', + options: { + presets: [ + '\'es2015\'' + ] + } }; }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index dd3841f7cf0..274ca3bf803 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -1,14 +1,13 @@ const Generator = require('yeoman-generator'); -const chalk = require('chalk'); const createCommonsChunkPlugin = require('webpack-addons').createCommonsChunkPlugin; const Input = require('webpack-addons').Input; const InputValidate = require('webpack-addons').InputValidate; -const RawList = require('webpack-addons').RawList; +const Confirm = require('webpack-addons').Confirm; const entryQuestions = require('./utils/entry'); -const getDefaultLoaders = require('./utils/module'); +const getBabelPlugin = require('./utils/module'); const getDefaultPlugins = require('./utils/plugins'); const tooltip = require('./utils/tooltip'); const validate = require('./utils/validate'); @@ -16,6 +15,7 @@ const validate = require('./utils/validate'); module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { super(args, opts); + this.npmInstalls = ['uglifyjs-webpack-plugin']; this.configuration = { config: { webpackOptions: {}, @@ -29,15 +29,13 @@ module.exports = class WebpackGenerator extends Generator { let self = this; let oneOrMoreEntries; - this.configuration.config.webpackOptions.module = getDefaultLoaders(); + this.configuration.config.webpackOptions.module = { + rules: [] + }; this.configuration.config.webpackOptions.plugins = getDefaultPlugins(); this.configuration.config.topScope.push(tooltip.uglify()); this.prompt([ - RawList( - 'entryType', - 'Will you be creating multiple bundles?', - ['Yes', 'No'] - ) + Confirm('entryType', 'Will you be creating multiple bundles?') ]).then( (entryTypeAnswer) => { // Ask different questions for entry points entryQuestions(self, entryTypeAnswer).then(entryOptions => { @@ -65,71 +63,59 @@ module.exports = class WebpackGenerator extends Generator { } this.configuration.config.webpackOptions.output.path = `'${outputTypeAnswer['outputType']}'`; }).then( () => { - // Ask if the user wants to use extractPlugin this.prompt([ - Input( - 'extractPlugin', - 'What\'s the name of your css file? (press enter to skip)' - ) - ]).then( (extractAnswer) => { - if(extractAnswer['extractPlugin'].length !== 0) { - this.configuration.config.topScope.push(tooltip.cssPlugin()); - this.configuration.config.webpackOptions.plugins.push( - 'new ExtractTextPlugin(\'' + extractAnswer['extractPlugin'] + '.css\')' - ); - this.configuration.config.webpackOptions.module.rules.push({ - test: new RegExp(/\.css$/), - use: `ExtractTextPlugin.extract({ - fallback: 'style-loader', - use: 'css-loader' - })` - }); - this.configuration.config.topScope.push( - 'const ExtractTextPlugin = require(\'extract-text-webpack-plugin\');' - ); + Confirm('babelConfirm', 'Will you be using ES2015?') + ]).then( (ans) => { + if(ans['babelConfirm'] === true) { + this.configuration.config.webpackOptions.module.rules.push(getBabelPlugin()); + this.npmInstalls = ['babel-loader', 'babel-core', 'babel-preset-env']; } - }).then( () => { - if(!this.configuration.config.webpackOptions.entry.length) { - oneOrMoreEntries.forEach( (prop) => { + }).then(() => { + // Ask if the user wants to use extractPlugin + this.prompt([ + Input( + 'extractPlugin', + 'What\'s the name of your css file? (press enter to skip)' + ) + ]).then( (extractAnswer) => { + if(extractAnswer['extractPlugin'].length !== 0) { + this.configuration.config.topScope.push(tooltip.cssPlugin()); + this.npmInstalls.push('extract-text-webpack-plugin', 'style-loader', 'css-loader'); this.configuration.config.webpackOptions.plugins.push( - createCommonsChunkPlugin(prop) + 'new ExtractTextPlugin(\'' + extractAnswer['extractPlugin'] + '.css\')' ); - }); - } - this.configuration.config.topScope.push( - 'const UglifyJSPlugin = require(\'uglifyjs-webpack-plugin\');', - '\n' - ); - done(); + this.configuration.config.webpackOptions.module.rules.push({ + test: new RegExp(/\.css$/), + use: `ExtractTextPlugin.extract({ + fallback: 'style-loader', + use: 'css-loader' + })` + }); + this.configuration.config.topScope.push( + 'const ExtractTextPlugin = require(\'extract-text-webpack-plugin\');' + ); + } + }).then( () => { + if(!this.configuration.config.webpackOptions.entry.length) { + oneOrMoreEntries.forEach( (prop) => { + this.configuration.config.webpackOptions.plugins.push( + createCommonsChunkPlugin(prop) + ); + }); + } + this.configuration.config.topScope.push( + 'const UglifyJSPlugin = require(\'uglifyjs-webpack-plugin\');', + '\n' + ); + done(); + }); }); }); }); }); } installPlugins() { - let asyncDone = this.async(); - this.npmInstall(['uglifyjs-webpack-plugin'], { 'save-dev': true }); - this.configuration.config.webpackOptions.plugins.forEach( (plugin) => { - if(plugin.indexOf('new ExtractTextPlugin') >= 0) { - this.npmInstall(['extract-text-webpack-plugin'], { 'save-dev': true }); - } - }); - this.prompt([ - RawList( - 'finish', - 'Everything is set! Do you want to create your webpack.config.js?', - ['Yes', 'No'] - ) - ]).then( (answer) => { - if(answer['finish'] === 'Yes') { - asyncDone(); - } else { - process.stdout.write( - chalk.bold.red('\nInitializing aborted, run \'webpack init\' again if this was not intended.\n') - ); - process.exitCode = 0; - } - }); + this.npmInstall(this.npmInstalls, { 'save-dev': true }); } }; diff --git a/package.json b/package.json index 39ef6175b9d..7bbb02bb924 100644 --- a/package.json +++ b/package.json @@ -49,7 +49,7 @@ "resolve-cwd": "^2.0.0", "supports-color": "^3.1.2", "webpack": "^2.2.0-rc.0", - "webpack-addons": "^1.1.1", + "webpack-addons": "^1.1.2", "yargs": "^6.5.0", "yeoman-environment": "^1.6.6", "yeoman-generator": "git://github.com/ev1stensberg/generator.git#Feature-getArgument" From a9ea4330b9842f7688d68096dd61767611a5e9d5 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 7 May 2017 18:41:21 +0200 Subject: [PATCH 095/101] enhancements: add styling option to generator --- lib/creator/yeoman/utils/entry.js | 2 +- lib/creator/yeoman/utils/tooltip.js | 17 +++ lib/creator/yeoman/webpack-generator.js | 185 ++++++++++++++++++++---- 3 files changed, 171 insertions(+), 33 deletions(-) diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 8fde05ed914..74717580e14 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -68,7 +68,7 @@ module.exports = (self, answer) => { 'Where is the bundle you want to use located?', validate ) - ]).then( (singularAnswer) => `'${singularAnswer['singularEntry']}.js'`); + ]).then( (singularAnswer) => `'${singularAnswer['singularEntry']}'`); } return result; }; diff --git a/lib/creator/yeoman/utils/tooltip.js b/lib/creator/yeoman/utils/tooltip.js index 9d6d6c0d438..f7b24a8af21 100644 --- a/lib/creator/yeoman/utils/tooltip.js +++ b/lib/creator/yeoman/utils/tooltip.js @@ -27,6 +27,23 @@ module.exports = { * * https://github.com/webpack-contrib/extract-text-webpack-plugin * + */`); + }, + postcss: () => { + return( + `/* + * We've enabled Postcss, autoprefixer and precss for you. This allows your app + * to lint CSS, support variables and mixins, transpile future CSS syntax, + * inline images, and more! + * + * To enable SASS or LESS, add a the respective loaders to module.rules + * + * https://github.com/postcss/postcss + * + * https://github.com/postcss/autoprefixer + * + * https://github.com/jonathantneal/precss + * */`); } }; diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 274ca3bf803..f10e8d266ef 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -5,6 +5,7 @@ const createCommonsChunkPlugin = require('webpack-addons').createCommonsChunkPlu const Input = require('webpack-addons').Input; const InputValidate = require('webpack-addons').InputValidate; const Confirm = require('webpack-addons').Confirm; +const RawList = require('webpack-addons').RawList; const entryQuestions = require('./utils/entry'); const getBabelPlugin = require('./utils/module'); @@ -28,12 +29,18 @@ module.exports = class WebpackGenerator extends Generator { let done = this.async(); let self = this; let oneOrMoreEntries; + let regExpForStyles; + let ExtractUseProps; this.configuration.config.webpackOptions.module = { rules: [] }; this.configuration.config.webpackOptions.plugins = getDefaultPlugins(); - this.configuration.config.topScope.push(tooltip.uglify()); + this.configuration.config.topScope.push( + tooltip.uglify(), + 'const UglifyJSPlugin = require(\'uglifyjs-webpack-plugin\');', + '\n' + ); this.prompt([ Confirm('entryType', 'Will you be creating multiple bundles?') ]).then( (entryTypeAnswer) => { @@ -70,44 +77,148 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.config.webpackOptions.module.rules.push(getBabelPlugin()); this.npmInstalls = ['babel-loader', 'babel-core', 'babel-preset-env']; } - }).then(() => { - // Ask if the user wants to use extractPlugin + }).then( () => { this.prompt([ - Input( - 'extractPlugin', - 'What\'s the name of your css file? (press enter to skip)' + RawList( + 'stylingType', + 'Will you use one of the below CSS solutions?', + ['SASS', 'LESS', 'CSS', 'PostCSS', 'No'] ) - ]).then( (extractAnswer) => { - if(extractAnswer['extractPlugin'].length !== 0) { - this.configuration.config.topScope.push(tooltip.cssPlugin()); - this.npmInstalls.push('extract-text-webpack-plugin', 'style-loader', 'css-loader'); - this.configuration.config.webpackOptions.plugins.push( - 'new ExtractTextPlugin(\'' + extractAnswer['extractPlugin'] + '.css\')' + ]).then( (stylingAnswer) => { + if(stylingAnswer['stylingType'] === 'SASS') { + this.npmInstalls.push( + 'sass-loader', 'node-sass', + 'style-loader', 'css-loader' ); - this.configuration.config.webpackOptions.module.rules.push({ - test: new RegExp(/\.css$/), - use: `ExtractTextPlugin.extract({ - fallback: 'style-loader', - use: 'css-loader' - })` - }); + regExpForStyles = new RegExp(/\.(scss|css)$/); + ExtractUseProps = `use: [{ + loader: 'css-loader', + options: { + sourceMap: true + } + }, { + loader: 'sass-loader', + options: { + sourceMap: true + } + }], + fallback: 'style-loader'`; + } + else if(stylingAnswer['stylingType'] === 'LESS') { + regExpForStyles = new RegExp(/\.(less|css)$/); + this.npmInstalls.push( + 'less-loader', 'less', + 'style-loader', 'css-loader' + ); + ExtractUseProps = ` + use: [{ + loader: 'css-loader', + options: { + sourceMap: true + } + }, { + loader: 'less-loader', + options: { + sourceMap: true + } + }], + fallback: 'style-loader'`; + + } + else if(stylingAnswer['stylingType'] === 'PostCSS') { this.configuration.config.topScope.push( - 'const ExtractTextPlugin = require(\'extract-text-webpack-plugin\');' + tooltip.postcss(), + 'const autoprefixer = require(\'autoprefixer\');', + 'const precss = require(\'precss\');' + ); + this.npmInstalls.push( + 'style-loader', 'css-loader', + 'postcss-loader', 'precss', + 'autoprefixer' ); + regExpForStyles = new RegExp(/\.css$/); + ExtractUseProps = ` + use: [{ + loader: 'style-loader' + },{ + loader: 'css-loader', + options: { + sourceMap: true, + importLoaders: 1 + } + }, { + loader: 'postcss-loader', + options: { + sourceMap: 'inline', + plugins: function () { + return [ + precss, + autoprefixer + ]; + } + } + }], + fallback: 'style-loader'`; + } + else if(stylingAnswer['stylingType'] === 'CSS') { + this.npmInstalls.push('style-loader', 'css-loader'); + regExpForStyles = new RegExp(/\.css$/); + ExtractUseProps = `use: [{ + loader: 'css-loader', + options: { + sourceMap: true + } + }], + fallback: 'style-loader'`; + } + else { + regExpForStyles = null; } }).then( () => { - if(!this.configuration.config.webpackOptions.entry.length) { - oneOrMoreEntries.forEach( (prop) => { - this.configuration.config.webpackOptions.plugins.push( - createCommonsChunkPlugin(prop) + // Ask if the user wants to use extractPlugin + this.prompt([ + Input( + 'extractPlugin', + 'What\'s the name of your bundled css file? (press enter to skip)' + ) + ]).then( (extractAnswer) => { + if(regExpForStyles) { + this.configuration.config.topScope.push(tooltip.cssPlugin()); + this.npmInstalls.push('extract-text-webpack-plugin'); + if(extractAnswer['extractPlugin'].length !== 0) { + this.configuration.config.webpackOptions.plugins.push( + 'new ExtractTextPlugin(\'' + + extractAnswer['extractPlugin'] + + '.css\')' + ); + } else { + this.configuration.config.webpackOptions.plugins.push( + 'new ExtractTextPlugin(\'' + + 'style.css\')' + ); + } + const moduleRulesObj = { + test: regExpForStyles, + use: `ExtractTextPlugin.extract({ + ${ExtractUseProps} + })` + }; + this.configuration.config.webpackOptions.module.rules.push(moduleRulesObj); + this.configuration.config.topScope.push( + 'const ExtractTextPlugin = require(\'extract-text-webpack-plugin\');', + '\n' ); - }); - } - this.configuration.config.topScope.push( - 'const UglifyJSPlugin = require(\'uglifyjs-webpack-plugin\');', - '\n' - ); - done(); + } + }).then( () => { + if(!this.configuration.config.webpackOptions.entry.length) { + oneOrMoreEntries.forEach( (prop) => { + this.configuration.config.webpackOptions.plugins.push( + createCommonsChunkPlugin(prop) + ); + }); + } + done(); + }); }); }); }); @@ -115,7 +226,17 @@ module.exports = class WebpackGenerator extends Generator { }); } installPlugins() { - this.npmInstall(this.npmInstalls, { 'save-dev': true }); + let asyncNamePrompt = this.async(); + this.prompt([ + Input('nameType', 'Name your \'webpack.[name].js?\' [default: \'config\']:') + ]).then( (nameAnswer) => { + if(nameAnswer['nameType'].length) { + this.configuration.config.configName = nameAnswer['nameType']; + } + }).then( () => { + asyncNamePrompt(); + this.npmInstall(this.npmInstalls, { 'save-dev': true }); + }); } }; From bc24b9e4b3fa19bc16c7742030935d54aa7366bb Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 7 May 2017 19:14:39 +0200 Subject: [PATCH 096/101] fix: remove sourceMap from postcss prop --- lib/creator/yeoman/webpack-generator.js | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index f10e8d266ef..1c13f0044c7 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -149,7 +149,6 @@ module.exports = class WebpackGenerator extends Generator { }, { loader: 'postcss-loader', options: { - sourceMap: 'inline', plugins: function () { return [ precss, From f4add5ae4b83ec9c94910b8ef9113af9be47324e Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 7 May 2017 20:23:58 +0200 Subject: [PATCH 097/101] enhancements: separate dev and prod build --- lib/creator/yeoman/utils/tooltip.js | 2 +- lib/creator/yeoman/webpack-generator.js | 351 +++++++++++++++--------- 2 files changed, 219 insertions(+), 134 deletions(-) diff --git a/lib/creator/yeoman/utils/tooltip.js b/lib/creator/yeoman/utils/tooltip.js index f7b24a8af21..041966d9a2f 100644 --- a/lib/creator/yeoman/utils/tooltip.js +++ b/lib/creator/yeoman/utils/tooltip.js @@ -36,7 +36,7 @@ module.exports = { * to lint CSS, support variables and mixins, transpile future CSS syntax, * inline images, and more! * - * To enable SASS or LESS, add a the respective loaders to module.rules + * To enable SASS or LESS, add the respective loaders to module.rules * * https://github.com/postcss/postcss * diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 1c13f0044c7..0981fe7b796 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -16,6 +16,7 @@ const validate = require('./utils/validate'); module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { super(args, opts); + this.isProd = false; this.npmInstalls = ['uglifyjs-webpack-plugin']; this.configuration = { config: { @@ -71,152 +72,233 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.config.webpackOptions.output.path = `'${outputTypeAnswer['outputType']}'`; }).then( () => { this.prompt([ - Confirm('babelConfirm', 'Will you be using ES2015?') - ]).then( (ans) => { - if(ans['babelConfirm'] === true) { - this.configuration.config.webpackOptions.module.rules.push(getBabelPlugin()); - this.npmInstalls = ['babel-loader', 'babel-core', 'babel-preset-env']; + Confirm('prodConfirm', 'Are you going to use this in production?') + ]).then( (prodAnswer) => { + if(prodAnswer['prodConfirm'] === true) { + this.isProd = true; + } else { + this.isProd = false; } }).then( () => { this.prompt([ - RawList( - 'stylingType', - 'Will you use one of the below CSS solutions?', - ['SASS', 'LESS', 'CSS', 'PostCSS', 'No'] - ) - ]).then( (stylingAnswer) => { - if(stylingAnswer['stylingType'] === 'SASS') { - this.npmInstalls.push( - 'sass-loader', 'node-sass', - 'style-loader', 'css-loader' - ); - regExpForStyles = new RegExp(/\.(scss|css)$/); - ExtractUseProps = `use: [{ - loader: 'css-loader', - options: { - sourceMap: true - } - }, { - loader: 'sass-loader', - options: { - sourceMap: true - } - }], - fallback: 'style-loader'`; - } - else if(stylingAnswer['stylingType'] === 'LESS') { - regExpForStyles = new RegExp(/\.(less|css)$/); - this.npmInstalls.push( - 'less-loader', 'less', - 'style-loader', 'css-loader' - ); - ExtractUseProps = ` - use: [{ - loader: 'css-loader', - options: { - sourceMap: true - } - }, { - loader: 'less-loader', - options: { - sourceMap: true - } - }], - fallback: 'style-loader'`; - - } - else if(stylingAnswer['stylingType'] === 'PostCSS') { - this.configuration.config.topScope.push( - tooltip.postcss(), - 'const autoprefixer = require(\'autoprefixer\');', - 'const precss = require(\'precss\');' - ); - this.npmInstalls.push( - 'style-loader', 'css-loader', - 'postcss-loader', 'precss', - 'autoprefixer' - ); - regExpForStyles = new RegExp(/\.css$/); - ExtractUseProps = ` - use: [{ - loader: 'style-loader' - },{ - loader: 'css-loader', - options: { - sourceMap: true, - importLoaders: 1 - } - }, { - loader: 'postcss-loader', - options: { - plugins: function () { - return [ - precss, - autoprefixer - ]; - } - } - }], - fallback: 'style-loader'`; - } - else if(stylingAnswer['stylingType'] === 'CSS') { - this.npmInstalls.push('style-loader', 'css-loader'); - regExpForStyles = new RegExp(/\.css$/); - ExtractUseProps = `use: [{ - loader: 'css-loader', - options: { - sourceMap: true - } - }], - fallback: 'style-loader'`; - } - else { - regExpForStyles = null; + Confirm('babelConfirm', 'Will you be using ES2015?') + ]).then( (ans) => { + if(ans['babelConfirm'] === true) { + this.configuration.config.webpackOptions.module.rules.push(getBabelPlugin()); + this.npmInstalls = ['babel-loader', 'babel-core', 'babel-preset-env']; } }).then( () => { - // Ask if the user wants to use extractPlugin this.prompt([ - Input( - 'extractPlugin', - 'What\'s the name of your bundled css file? (press enter to skip)' + RawList( + 'stylingType', + 'Will you use one of the below CSS solutions?', + ['SASS', 'LESS', 'CSS', 'PostCSS', 'No'] ) - ]).then( (extractAnswer) => { - if(regExpForStyles) { - this.configuration.config.topScope.push(tooltip.cssPlugin()); - this.npmInstalls.push('extract-text-webpack-plugin'); - if(extractAnswer['extractPlugin'].length !== 0) { - this.configuration.config.webpackOptions.plugins.push( - 'new ExtractTextPlugin(\'' + - extractAnswer['extractPlugin'] + - '.css\')' - ); + ]).then( (stylingAnswer) => { + if(!this.isProd) { + ExtractUseProps = []; + } + if(stylingAnswer['stylingType'] === 'SASS') { + this.npmInstalls.push( + 'sass-loader', 'node-sass', + 'style-loader', 'css-loader' + ); + regExpForStyles = new RegExp(/\.(scss|css)$/); + if(this.isProd) { + ExtractUseProps = `use: [{ + loader: 'css-loader', + options: { + sourceMap: true + } + }, { + loader: 'sass-loader', + options: { + sourceMap: true + } + }], + fallback: 'style-loader'`; } else { - this.configuration.config.webpackOptions.plugins.push( - 'new ExtractTextPlugin(\'' + - 'style.css\')' - ); + ExtractUseProps.push({ + loader: '\'style-loader\'' + }, { + loader: '\'css-loader\'' + }, { + loader: '\'sass-loader\'' + }); } - const moduleRulesObj = { - test: regExpForStyles, - use: `ExtractTextPlugin.extract({ - ${ExtractUseProps} - })` - }; - this.configuration.config.webpackOptions.module.rules.push(moduleRulesObj); + } + else if(stylingAnswer['stylingType'] === 'LESS') { + regExpForStyles = new RegExp(/\.(less|css)$/); + this.npmInstalls.push( + 'less-loader', 'less', + 'style-loader', 'css-loader' + ); + if(this.isProd) { + ExtractUseProps = ` + use: [{ + loader: 'css-loader', + options: { + sourceMap: true + } + }, { + loader: 'less-loader', + options: { + sourceMap: true + } + }], + fallback: 'style-loader'`; + } else { + ExtractUseProps.push({ + loader: '\'css-loader\'', + options: { + sourceMap: true + } + }, { + loader: '\'less-loader\'', + options: { + sourceMap: true + } + }); + } + } + else if(stylingAnswer['stylingType'] === 'PostCSS') { this.configuration.config.topScope.push( - 'const ExtractTextPlugin = require(\'extract-text-webpack-plugin\');', + tooltip.postcss(), + 'const autoprefixer = require(\'autoprefixer\');', + 'const precss = require(\'precss\');', '\n' ); + this.npmInstalls.push( + 'style-loader', 'css-loader', + 'postcss-loader', 'precss', + 'autoprefixer' + ); + regExpForStyles = new RegExp(/\.css$/); + if(this.isProd) { + ExtractUseProps = ` + use: [{ + loader: 'style-loader' + },{ + loader: 'css-loader', + options: { + sourceMap: true, + importLoaders: 1 + } + }, { + loader: 'postcss-loader', + options: { + plugins: function () { + return [ + precss, + autoprefixer + ]; + } + } + }], + fallback: 'style-loader'`; + } else { + ExtractUseProps.push({ + loader: '\'style-loader\'' + },{ + loader: '\'css-loader\'', + options: { + sourceMap: true, + importLoaders: 1 + } + }, { + loader: '\'postcss-loader\'', + options: { + plugins: `function () { + return [ + precss, + autoprefixer + ]; + }` + } + }); + } } - }).then( () => { - if(!this.configuration.config.webpackOptions.entry.length) { - oneOrMoreEntries.forEach( (prop) => { - this.configuration.config.webpackOptions.plugins.push( - createCommonsChunkPlugin(prop) - ); - }); + else if(stylingAnswer['stylingType'] === 'CSS') { + this.npmInstalls.push('style-loader', 'css-loader'); + regExpForStyles = new RegExp(/\.css$/); + if(this.isProd) { + ExtractUseProps = `use: [{ + loader: 'css-loader', + options: { + sourceMap: true + } + }], + fallback: 'style-loader'`; + } else { + ExtractUseProps.push({ + loader: '\'css-loader\'', + options: { + sourceMap: true + } + }); + } + } + else { + regExpForStyles = null; } - done(); + }).then( () => { + // Ask if the user wants to use extractPlugin + this.prompt([ + Input( + 'extractPlugin', + 'What\'s the name of your bundled css file? (press enter to skip)' + ) + ]).then( (extractAnswer) => { + if(regExpForStyles) { + if(this.isProd) { + + this.configuration.config.topScope.push(tooltip.cssPlugin()); + this.npmInstalls.push('extract-text-webpack-plugin'); + if(extractAnswer['extractPlugin'].length !== 0) { + this.configuration.config.webpackOptions.plugins.push( + 'new ExtractTextPlugin(\'' + + extractAnswer['extractPlugin'] + + '.css\')' + ); + } else { + this.configuration.config.webpackOptions.plugins.push( + 'new ExtractTextPlugin(\'' + + 'style.css\')' + ); + } + const moduleRulesObj = { + test: regExpForStyles, + use: `ExtractTextPlugin.extract({ + ${ExtractUseProps} + })` + }; + this.configuration.config.webpackOptions.module.rules.push( + moduleRulesObj + ); + this.configuration.config.topScope.push( + 'const ExtractTextPlugin = require(\'extract-text-webpack-plugin\');', + '\n' + ); + } else { + const moduleRulesObj = { + test: regExpForStyles, + use: ExtractUseProps + }; + this.configuration.config.webpackOptions.module.rules.push( + moduleRulesObj + ); + } + } + }).then( () => { + if(!this.configuration.config.webpackOptions.entry.length) { + oneOrMoreEntries.forEach( (prop) => { + this.configuration.config.webpackOptions.plugins.push( + createCommonsChunkPlugin(prop) + ); + }); + } + done(); + }); }); }); }); @@ -226,11 +308,14 @@ module.exports = class WebpackGenerator extends Generator { } installPlugins() { let asyncNamePrompt = this.async(); + let defaultName = this.isProd ? 'prod' : 'config'; this.prompt([ - Input('nameType', 'Name your \'webpack.[name].js?\' [default: \'config\']:') + Input('nameType', `Name your \'webpack.[name].js?\' [default: \'${defaultName}\']:`) ]).then( (nameAnswer) => { if(nameAnswer['nameType'].length) { this.configuration.config.configName = nameAnswer['nameType']; + } else { + this.configuration.config.configName = defaultName; } }).then( () => { asyncNamePrompt(); From c766779ea6f971e3612f5f6cd868627d1adb9395 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 7 May 2017 20:58:00 +0200 Subject: [PATCH 098/101] enhancements: add contentHash & name --- lib/creator/yeoman/webpack-generator.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 0981fe7b796..7ea24fdd267 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -61,8 +61,8 @@ module.exports = class WebpackGenerator extends Generator { if(!this.configuration.config.webpackOptions.entry.length) { this.configuration.config.topScope.push(tooltip.commonsChunk()); this.configuration.config.webpackOptions.output = { - filename: '\'[name]-[chunkhash].js\'', - chunkFilename: '\'[chunkhash].js\'' + filename: '\'[name].[chunkhash].js\'', + chunkFilename: '\'[name].[chunkhash].js\'' }; } else { this.configuration.config.webpackOptions.output = { @@ -258,7 +258,7 @@ module.exports = class WebpackGenerator extends Generator { this.configuration.config.webpackOptions.plugins.push( 'new ExtractTextPlugin(\'' + extractAnswer['extractPlugin'] + - '.css\')' + '.[contentHash].css\')' ); } else { this.configuration.config.webpackOptions.plugins.push( From ef0592801aaf48227e181967bf3df118bbd4c276 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 7 May 2017 22:16:35 +0200 Subject: [PATCH 099/101] enhancements: prompt for better answers --- lib/creator/yeoman/utils/entry.js | 2 +- lib/creator/yeoman/webpack-generator.js | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index 74717580e14..ef607dd0e59 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -65,7 +65,7 @@ module.exports = (self, answer) => { result = self.prompt([ InputValidate( 'singularEntry', - 'Where is the bundle you want to use located?', + 'Which module will be the first to enter the application?', validate ) ]).then( (singularAnswer) => `'${singularAnswer['singularEntry']}'`); diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 7ea24fdd267..b55cd84a3c3 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -3,7 +3,6 @@ const Generator = require('yeoman-generator'); const createCommonsChunkPlugin = require('webpack-addons').createCommonsChunkPlugin; const Input = require('webpack-addons').Input; -const InputValidate = require('webpack-addons').InputValidate; const Confirm = require('webpack-addons').Confirm; const RawList = require('webpack-addons').RawList; @@ -52,10 +51,9 @@ module.exports = class WebpackGenerator extends Generator { }).then( () => { this.prompt([ - InputValidate( + Input( 'outputType', - 'What folder do you want to put those files in?', - validate + 'Which folder will your generated bundles be in? [default: dist]:' ) ]).then( (outputTypeAnswer) => { if(!this.configuration.config.webpackOptions.entry.length) { @@ -69,7 +67,11 @@ module.exports = class WebpackGenerator extends Generator { filename: '\'[name].bundle.js\'', }; } - this.configuration.config.webpackOptions.output.path = `'${outputTypeAnswer['outputType']}'`; + if(outputTypeAnswer['outputType'].length) { + this.configuration.config.webpackOptions.output.path = `'${outputTypeAnswer['outputType']}'`; + } else { + this.configuration.config.webpackOptions.output.path = '\'./dist\''; + } }).then( () => { this.prompt([ Confirm('prodConfirm', 'Are you going to use this in production?') @@ -246,7 +248,7 @@ module.exports = class WebpackGenerator extends Generator { this.prompt([ Input( 'extractPlugin', - 'What\'s the name of your bundled css file? (press enter to skip)' + 'If you want to bundle your CSS files, what will you name it? (press enter to skip)' ) ]).then( (extractAnswer) => { if(regExpForStyles) { From 2e2a38f869b97157c75a042bda3cd5866fe38e13 Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 7 May 2017 22:41:59 +0200 Subject: [PATCH 100/101] fix: remove unused module --- lib/creator/yeoman/webpack-generator.js | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index b55cd84a3c3..4fc010cbb14 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -10,7 +10,6 @@ const entryQuestions = require('./utils/entry'); const getBabelPlugin = require('./utils/module'); const getDefaultPlugins = require('./utils/plugins'); const tooltip = require('./utils/tooltip'); -const validate = require('./utils/validate'); module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { From dd9b89483510d067f544cba170a20c9f6f62dcbc Mon Sep 17 00:00:00 2001 From: Even Stensberg Date: Sun, 7 May 2017 23:05:14 +0200 Subject: [PATCH 101/101] chore: final fixes before release --- README.md | 4 ++-- SCAFFOLDING.md | 2 +- lib/creator/yeoman/utils/entry.js | 2 +- lib/creator/yeoman/webpack-generator.js | 5 +++-- package.json | 2 +- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 16b9b078b4b..7b93947cf2c 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Webpack CLI encapsulates all code related to CLI handling. It captures options a The `migrate` feature eases the transition from [version 1](http://webpack.github.io/docs/) to [version 2](https://gist.github.com/sokra/27b24881210b56bbaff7). `migrate` also allows users to switch to the new version of webpack without having to extensively [refactor](https://webpack.js.org/guides/migrating/). -`webpack --migrate ` +`webpack-cli --migrate ` [Read more about migrating](MIGRATE.md) @@ -27,6 +27,6 @@ The `migrate` feature eases the transition from [version 1](http://webpack.githu The `init` feature allows users to get started with webpack, fast. Through scaffolding, people can create their own configuration in order to faster initialize new projects for various of use cases. -`webpack --init [webpack-addons-]` +`webpack-cli --init [webpack-addons-]` [Read more about scaffolding](SCAFFOLDING.md) diff --git a/SCAFFOLDING.md b/SCAFFOLDING.md index de17fcd641a..f5d06e1734e 100644 --- a/SCAFFOLDING.md +++ b/SCAFFOLDING.md @@ -2,7 +2,7 @@ Setting up webpack for the first time is hard. Writing advanced configurations to optimize performance is even harder. The `init` feature is designed to support people that want to create their own configuration or initializing other projects people create. -Through [yeoman](http://yeoman.io/), the `webpack --init` feature allows people to create scaffolds and generate new projects quickly. An npm dependency that scaffolds a `webpack.config.js` through `webpack-cli` is what we refer to as an **addon**. +Through [yeoman](http://yeoman.io/), the `webpack-cli --init` feature allows people to create scaffolds and generate new projects quickly. An npm dependency that scaffolds a `webpack.config.js` through `webpack-cli` is what we refer to as an **addon**. ## Writing a good scaffold diff --git a/lib/creator/yeoman/utils/entry.js b/lib/creator/yeoman/utils/entry.js index ef607dd0e59..f1f2839e8f7 100644 --- a/lib/creator/yeoman/utils/entry.js +++ b/lib/creator/yeoman/utils/entry.js @@ -8,7 +8,7 @@ module.exports = (self, answer) => { result = self.prompt([ InputValidate( 'multipleEntries', - 'Type the name you want for your modules seperated by comma', + 'Type the name you want for your modules (entry files), seperated by comma', validate ) ]).then( (multipleEntriesAnswer) => { diff --git a/lib/creator/yeoman/webpack-generator.js b/lib/creator/yeoman/webpack-generator.js index 4fc010cbb14..de4587356fc 100644 --- a/lib/creator/yeoman/webpack-generator.js +++ b/lib/creator/yeoman/webpack-generator.js @@ -15,7 +15,7 @@ module.exports = class WebpackGenerator extends Generator { constructor(args, opts) { super(args, opts); this.isProd = false; - this.npmInstalls = ['uglifyjs-webpack-plugin']; + this.npmInstalls = ['webpack', 'uglifyjs-webpack-plugin']; this.configuration = { config: { webpackOptions: {}, @@ -36,6 +36,7 @@ module.exports = class WebpackGenerator extends Generator { }; this.configuration.config.webpackOptions.plugins = getDefaultPlugins(); this.configuration.config.topScope.push( + 'const webpack = require(\'webpack\')', tooltip.uglify(), 'const UglifyJSPlugin = require(\'uglifyjs-webpack-plugin\');', '\n' @@ -247,7 +248,7 @@ module.exports = class WebpackGenerator extends Generator { this.prompt([ Input( 'extractPlugin', - 'If you want to bundle your CSS files, what will you name it? (press enter to skip)' + 'If you want to bundle your CSS files, what will you name the bundle? (press enter to skip)' ) ]).then( (extractAnswer) => { if(regExpForStyles) { diff --git a/package.json b/package.json index 7bbb02bb924..e7b98ddeff3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "webpack-cli", - "version": "0.0.1", + "version": "1.0.0", "description": "CLI for webpack & friends", "license": "MIT", "preferGlobal": true,