From f1feb0b298c5801bd88795d7cd3ef042da9f6ce8 Mon Sep 17 00:00:00 2001 From: Lyrkan <850046+Lyrkan@users.noreply.github.com> Date: Sun, 31 Mar 2019 00:11:00 +0100 Subject: [PATCH 1/5] Move proxy and WebpackConfig initialization outside of the index.js file --- index.js | 129 +++---------------------------------------- lib/EncoreProxy.js | 96 ++++++++++++++++++++++++++++++++ lib/WebpackConfig.js | 44 ++++++++++++++- 3 files changed, 145 insertions(+), 124 deletions(-) create mode 100644 lib/EncoreProxy.js diff --git a/index.js b/index.js index 4749101b..0021aee5 100644 --- a/index.js +++ b/index.js @@ -9,53 +9,15 @@ 'use strict'; +const EncoreProxy = require('./lib/EncoreProxy'); const WebpackConfig = require('./lib/WebpackConfig'); const configGenerator = require('./lib/config-generator'); const validator = require('./lib/config/validator'); -const prettyError = require('./lib/utils/pretty-error'); -const logger = require('./lib/logger'); const parseRuntime = require('./lib/config/parse-runtime'); -const chalk = require('chalk'); -const levenshtein = require('fast-levenshtein'); -const fs = require('fs'); -const path = require('path'); +const context = require('./lib/context'); -let webpackConfig = null; -let runtimeConfig = require('./lib/context').runtimeConfig; - -function initializeWebpackConfig() { - if (runtimeConfig.verbose) { - logger.verbose(); - } - - // Display a warning if webpack is listed as a [dev-]dependency - try { - const packageInfo = JSON.parse( - fs.readFileSync(path.resolve(runtimeConfig.context, 'package.json')) - ); - - if (packageInfo) { - const dependencies = new Set([ - ...(packageInfo.dependencies ? Object.keys(packageInfo.dependencies) : []), - ...(packageInfo.devDependencies ? Object.keys(packageInfo.devDependencies) : []), - ]); - - if (dependencies.has('webpack')) { - logger.warning('Webpack is already provided by Webpack Encore, also adding it to your package.json file may cause issues.'); - } - } - } catch (e) { - logger.warning('Could not read package.json file.'); - } - - webpackConfig = new WebpackConfig(runtimeConfig); -} - -// If runtimeConfig is already set webpackConfig can directly -// be initialized here. -if (runtimeConfig) { - initializeWebpackConfig(); -} +let runtimeConfig = context.runtimeConfig; +let webpackConfig = runtimeConfig ? new WebpackConfig(runtimeConfig, true) : null; class Encore { /** @@ -1288,7 +1250,7 @@ class Encore { process.cwd() ); - initializeWebpackConfig(); + webpackConfig = new WebpackConfig(runtimeConfig, true); return this; } @@ -1343,84 +1305,9 @@ class Encore { } } -// Proxy the API in order to prevent calls to most of its methods -// if the webpackConfig object hasn't been initialized yet. -const EncoreProxy = new Proxy(new Encore(), { - get: (target, prop) => { - if (prop === '__esModule') { - // When using Babel to preprocess a webpack.config.babel.js file - // (for instance if we want to use ES6 syntax) the __esModule - // property needs to be whitelisted to avoid an "Unknown property" - // error. - return target[prop]; - } - - if (typeof target[prop] === 'function') { - // These methods of the public API can be called even if the - // webpackConfig object hasn't been initialized yet. - const safeMethods = [ - 'configureRuntimeEnvironment', - 'clearRuntimeEnvironment', - 'isRuntimeEnvironmentConfigured', - ]; - - if (!webpackConfig && (safeMethods.indexOf(prop) === -1)) { - throw new Error(`Encore.${prop}() cannot be called yet because the runtime environment doesn't appear to be configured. Make sure you're using the encore executable or call Encore.configureRuntimeEnvironment() first if you're purposely not calling Encore directly.`); - } - - // Either a safe method has been called or the webpackConfig - // object is already available. In this case act as a passthrough. - return (...parameters) => { - try { - const res = target[prop](...parameters); - return (res === target) ? EncoreProxy : res; - } catch (error) { - prettyError(error); - process.exit(1); // eslint-disable-line - } - }; - } - - if (typeof target[prop] === 'undefined') { - // Find the property with the closest Levenshtein distance - let similarProperty; - let minDistance = Number.MAX_VALUE; - - for (const apiProperty of Object.getOwnPropertyNames(Encore.prototype)) { - // Ignore class constructor - if (apiProperty === 'constructor') { - continue; - } - - const distance = levenshtein.get(apiProperty, prop); - if (distance <= minDistance) { - similarProperty = apiProperty; - minDistance = distance; - } - } - - let errorMessage = `${chalk.red(`Encore.${prop}`)} is not a recognized property or method.`; - if (minDistance < (prop.length / 3)) { - errorMessage += ` Did you mean ${chalk.green(`Encore.${similarProperty}`)}?`; - } - - // Prettify the error message. - // Only keep the 2nd line of the stack trace: - // - First line should be this file (index.js) - // - Second line should be the Webpack config file - prettyError( - new Error(errorMessage), - { skipTrace: (traceLine, lineNumber) => lineNumber !== 1 } - ); - - process.exit(1); // eslint-disable-line - } - - return target[prop]; - } -}); - /** + * Proxy the API in order to prevent calls to most of its methods + * if the webpackConfig object hasn't been initialized yet. * @type {Encore} */ -module.exports = EncoreProxy; +module.exports = EncoreProxy.createProxy(new Encore()); diff --git a/lib/EncoreProxy.js b/lib/EncoreProxy.js new file mode 100644 index 00000000..65dc0b23 --- /dev/null +++ b/lib/EncoreProxy.js @@ -0,0 +1,96 @@ +/* + * This file is part of the Symfony Webpack Encore package. + * + * (c) Fabien Potencier + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +'use strict'; + +const chalk = require('chalk'); +const levenshtein = require('fast-levenshtein'); +const prettyError = require('./utils/pretty-error'); + +module.exports = { + createProxy: (Encore) => { + const EncoreProxy = new Proxy(Encore, { + get: (target, prop) => { + if (prop === '__esModule') { + // When using Babel to preprocess a webpack.config.babel.js file + // (for instance if we want to use ES6 syntax) the __esModule + // property needs to be whitelisted to avoid an "Unknown property" + // error. + return target[prop]; + } + + if (typeof target[prop] === 'function') { + // These methods of the public API can be called even if the + // webpackConfig object hasn't been initialized yet. + const safeMethods = [ + 'configureRuntimeEnvironment', + 'clearRuntimeEnvironment', + 'isRuntimeEnvironmentConfigured', + ]; + + if (!Encore.isRuntimeEnvironmentConfigured() && (safeMethods.indexOf(prop) === -1)) { + throw new Error(`Encore.${prop}() cannot be called yet because the runtime environment doesn't appear to be configured. Make sure you're using the encore executable or call Encore.configureRuntimeEnvironment() first if you're purposely not calling Encore directly.`); + } + + // Either a safe method has been called or the webpackConfig + // object is already available. In this case act as a passthrough. + return (...parameters) => { + try { + const res = target[prop](...parameters); + return (res === target) ? EncoreProxy : res; + } catch (error) { + prettyError(error); + process.exit(1); // eslint-disable-line + } + }; + } + + if (typeof target[prop] === 'undefined') { + // Find the property with the closest Levenshtein distance + let similarProperty; + let minDistance = Number.MAX_VALUE; + + const encorePrototype = Object.getPrototypeOf(Encore); + for (const apiProperty of Object.getOwnPropertyNames(encorePrototype)) { + // Ignore class constructor + if (apiProperty === 'constructor') { + continue; + } + + const distance = levenshtein.get(apiProperty, prop); + if (distance <= minDistance) { + similarProperty = apiProperty; + minDistance = distance; + } + } + + let errorMessage = `${chalk.red(`Encore.${prop}`)} is not a recognized property or method.`; + if (minDistance < (prop.length / 3)) { + errorMessage += ` Did you mean ${chalk.green(`Encore.${similarProperty}`)}?`; + } + + // Prettify the error message. + // Only keep the 2nd line of the stack trace: + // - First line should be the index.js file + // - Second line should be the Webpack config file + prettyError( + new Error(errorMessage), + { skipTrace: (traceLine, lineNumber) => lineNumber !== 1 } + ); + + process.exit(1); // eslint-disable-line + } + + return target[prop]; + } + }); + + return EncoreProxy; + } +}; diff --git a/lib/WebpackConfig.js b/lib/WebpackConfig.js index e7849897..140f022a 100644 --- a/lib/WebpackConfig.js +++ b/lib/WebpackConfig.js @@ -20,6 +20,10 @@ const logger = require('./logger'); */ function validateRuntimeConfig(runtimeConfig) { // if you're using the encore executable, these things should never happen + if (null === runtimeConfig) { + throw new Error('RuntimeConfig must be initialized'); + } + if (null === runtimeConfig.context) { throw new Error('RuntimeConfig.context must be set.'); } @@ -29,10 +33,44 @@ function validateRuntimeConfig(runtimeConfig) { } } +/** + * @param {RuntimeConfig} runtimeConfig + * @return {void} + */ +function checkPackageJson(runtimeConfig) { + // Display a warning if webpack is listed as a [dev-]dependency + try { + const packageInfo = JSON.parse( + fs.readFileSync(path.resolve(runtimeConfig.context, 'package.json')) + ); + + if (packageInfo) { + const dependencies = new Set([ + ...(packageInfo.dependencies ? Object.keys(packageInfo.dependencies) : []), + ...(packageInfo.devDependencies ? Object.keys(packageInfo.devDependencies) : []), + ]); + + if (dependencies.has('webpack')) { + logger.warning('Webpack is already provided by Webpack Encore, also adding it to your package.json file may cause issues.'); + } + } + } catch (e) { + logger.warning('Could not read package.json file.'); + } +} + class WebpackConfig { - constructor(runtimeConfig) { + constructor(runtimeConfig, enablePackageJsonCheck = false) { validateRuntimeConfig(runtimeConfig); + if (runtimeConfig.verbose) { + logger.verbose(); + } + + if (enablePackageJsonCheck) { + checkPackageJson(runtimeConfig); + } + this.runtimeConfig = runtimeConfig; this.entries = new Map(); this.styleEntries = new Map(); @@ -50,6 +88,8 @@ class WebpackConfig { this.aliases = {}; this.externals = []; this.integrityAlgorithms = []; + this.shouldUseSingleRuntimeChunk = null; + this.shouldSplitEntryChunks = false; // Features/Loaders flags this.useVersioning = false; @@ -96,8 +136,6 @@ class WebpackConfig { this.stylusLoaderOptionsCallback = () => {}; this.babelConfigurationCallback = () => {}; this.cssLoaderConfigurationCallback = () => {}; - this.shouldUseSingleRuntimeChunk = null; - this.shouldSplitEntryChunks = false; this.splitChunksConfigurationCallback = () => {}; this.watchOptionsConfigurationCallback = () => {}; this.vueLoaderOptionsCallback = () => {}; From 14a730b4964129e9c1ad9e53fb6aec1e06a5cfb5 Mon Sep 17 00:00:00 2001 From: Lyrkan <850046+Lyrkan@users.noreply.github.com> Date: Sun, 31 Mar 2019 00:18:46 +0100 Subject: [PATCH 2/5] Fix some JSDoc comments --- index.js | 2 +- lib/loaders/babel.js | 8 ++++---- lib/loaders/eslint.js | 8 ++++---- lib/loaders/handlebars.js | 8 ++++---- lib/loaders/less.js | 10 +++++----- lib/loaders/sass.js | 10 +++++----- lib/loaders/stylus.js | 10 +++++----- lib/loaders/typescript.js | 8 ++++---- lib/loaders/vue.js | 8 ++++---- 9 files changed, 36 insertions(+), 36 deletions(-) diff --git a/index.js b/index.js index 0021aee5..458aeb95 100644 --- a/index.js +++ b/index.js @@ -660,7 +660,7 @@ class Encore { * }); * * Supported options: - * * {bool} resolveUrlLoader (default=true) + * * {boolean} resolveUrlLoader (default=true) * Whether or not to use the resolve-url-loader. * Setting to false can increase performance in some * cases, especially when using bootstrap_sass. But, diff --git a/lib/loaders/babel.js b/lib/loaders/babel.js index a2e40cae..4e7240a7 100644 --- a/lib/loaders/babel.js +++ b/lib/loaders/babel.js @@ -12,11 +12,11 @@ const loaderFeatures = require('../features'); const applyOptionsCallback = require('../utils/apply-options-callback'); -/** - * @param {WebpackConfig} webpackConfig - * @return {Array} of loaders to use for Babel - */ module.exports = { + /** + * @param {WebpackConfig} webpackConfig + * @return {Array} of loaders to use for Babel + */ getLoaders(webpackConfig) { let babelConfig = { // improves performance by caching babel compiles diff --git a/lib/loaders/eslint.js b/lib/loaders/eslint.js index 260c0436..f3811153 100644 --- a/lib/loaders/eslint.js +++ b/lib/loaders/eslint.js @@ -12,11 +12,11 @@ const loaderFeatures = require('../features'); const applyOptionsCallback = require('../utils/apply-options-callback'); -/** - * @param {WebpackConfig} webpackConfig - * @return {Object} of options to use for eslint-loader options. - */ module.exports = { + /** + * @param {WebpackConfig} webpackConfig + * @return {Object} of options to use for eslint-loader options. + */ getOptions(webpackConfig) { loaderFeatures.ensurePackagesExistAndAreCorrectVersion('eslint'); diff --git a/lib/loaders/handlebars.js b/lib/loaders/handlebars.js index 12ac5328..95731ce9 100644 --- a/lib/loaders/handlebars.js +++ b/lib/loaders/handlebars.js @@ -12,11 +12,11 @@ const loaderFeatures = require('../features'); const applyOptionsCallback = require('../utils/apply-options-callback'); -/** - * @param {WebpackConfig} webpackConfig - * @return {Array} of loaders to use for Handlebars - */ module.exports = { + /** + * @param {WebpackConfig} webpackConfig + * @return {Array} of loaders to use for Handlebars + */ getLoaders(webpackConfig) { loaderFeatures.ensurePackagesExistAndAreCorrectVersion('handlebars'); diff --git a/lib/loaders/less.js b/lib/loaders/less.js index 4d412f3b..753f3045 100644 --- a/lib/loaders/less.js +++ b/lib/loaders/less.js @@ -13,12 +13,12 @@ const loaderFeatures = require('../features'); const cssLoader = require('./css'); const applyOptionsCallback = require('../utils/apply-options-callback'); -/** - * @param {WebpackConfig} webpackConfig - * @param {bool} useCssModules - * @return {Array} of loaders to use for Less files - */ module.exports = { + /** + * @param {WebpackConfig} webpackConfig + * @param {boolean} useCssModules + * @return {Array} of loaders to use for Less files + */ getLoaders(webpackConfig, useCssModules = false) { loaderFeatures.ensurePackagesExistAndAreCorrectVersion('less'); diff --git a/lib/loaders/sass.js b/lib/loaders/sass.js index 052c8298..6d3ec9de 100644 --- a/lib/loaders/sass.js +++ b/lib/loaders/sass.js @@ -13,12 +13,12 @@ const loaderFeatures = require('../features'); const cssLoader = require('./css'); const applyOptionsCallback = require('../utils/apply-options-callback'); -/** - * @param {WebpackConfig} webpackConfig - * @param {bool} useCssModules - * @return {Array} of loaders to use for Sass files - */ module.exports = { + /** + * @param {WebpackConfig} webpackConfig + * @param {boolean} useCssModules + * @return {Array} of loaders to use for Sass files + */ getLoaders(webpackConfig, useCssModules = false) { loaderFeatures.ensurePackagesExistAndAreCorrectVersion('sass'); diff --git a/lib/loaders/stylus.js b/lib/loaders/stylus.js index 5b19a585..7aaa7084 100644 --- a/lib/loaders/stylus.js +++ b/lib/loaders/stylus.js @@ -13,12 +13,12 @@ const loaderFeatures = require('../features'); const cssLoader = require('./css'); const applyOptionsCallback = require('../utils/apply-options-callback'); -/** - * @param {WebpackConfig} webpackConfig - * @param {bool} useCssModules - * @return {Array} of loaders to use for Stylus files - */ module.exports = { + /** + * @param {WebpackConfig} webpackConfig + * @param {boolean} useCssModules + * @return {Array} of loaders to use for Stylus files + */ getLoaders(webpackConfig, useCssModules = false) { loaderFeatures.ensurePackagesExistAndAreCorrectVersion('stylus'); diff --git a/lib/loaders/typescript.js b/lib/loaders/typescript.js index a0fc31fa..68d4accc 100644 --- a/lib/loaders/typescript.js +++ b/lib/loaders/typescript.js @@ -13,11 +13,11 @@ const loaderFeatures = require('../features'); const babelLoader = require('./babel'); const applyOptionsCallback = require('../utils/apply-options-callback'); -/** - * @param {WebpackConfig} webpackConfig - * @return {Array} of loaders to use for TypeScript - */ module.exports = { + /** + * @param {WebpackConfig} webpackConfig + * @return {Array} of loaders to use for TypeScript + */ getLoaders(webpackConfig) { loaderFeatures.ensurePackagesExistAndAreCorrectVersion('typescript'); diff --git a/lib/loaders/vue.js b/lib/loaders/vue.js index 5f214255..1c8a851d 100644 --- a/lib/loaders/vue.js +++ b/lib/loaders/vue.js @@ -12,11 +12,11 @@ const loaderFeatures = require('../features'); const applyOptionsCallback = require('../utils/apply-options-callback'); -/** - * @param {WebpackConfig} webpackConfig - * @return {Array} of loaders to use for Vue files - */ module.exports = { + /** + * @param {WebpackConfig} webpackConfig + * @return {Array} of loaders to use for Vue files + */ getLoaders(webpackConfig) { loaderFeatures.ensurePackagesExistAndAreCorrectVersion('vue'); From 1829c26187e795c9803c28fccb7f44b3bc2791d1 Mon Sep 17 00:00:00 2001 From: Lyrkan <850046+Lyrkan@users.noreply.github.com> Date: Sun, 31 Mar 2019 01:07:24 +0100 Subject: [PATCH 3/5] Remove some type warnings/inconsistencies --- bin/encore.js | 4 ++-- index.js | 12 ++++++++++-- lib/EncoreProxy.js | 8 +++++++- lib/WebpackConfig.js | 5 +++-- lib/config-generator.js | 1 + lib/config/RuntimeConfig.js | 6 ++++-- lib/config/parse-runtime.js | 4 ---- lib/config/path-util.js | 1 + lib/config/validator.js | 1 + lib/friendly-errors/asset-output-display-plugin.js | 2 +- lib/friendly-errors/formatters/missing-css-file.js | 2 +- lib/friendly-errors/formatters/missing-loader.js | 2 +- .../formatters/missing-postcss-config.js | 2 +- lib/loaders/babel.js | 1 + lib/loaders/css-extract.js | 1 + lib/loaders/css.js | 1 + lib/loaders/eslint.js | 1 + lib/loaders/handlebars.js | 1 + lib/loaders/less.js | 1 + lib/loaders/sass.js | 1 + lib/loaders/stylus.js | 1 + lib/loaders/typescript.js | 1 + lib/loaders/vue.js | 1 + lib/logger.js | 2 +- lib/package-helper.js | 4 ++-- lib/plugins/asset-output-display.js | 2 ++ lib/plugins/clean.js | 1 + lib/plugins/define.js | 1 + lib/plugins/delete-unused-entries.js | 1 + lib/plugins/entry-files-manifest.js | 1 + lib/plugins/forked-ts-types.js | 1 + lib/plugins/friendly-errors.js | 1 + lib/plugins/manifest.js | 1 + lib/plugins/mini-css-extract.js | 1 + lib/plugins/notifier.js | 1 + lib/plugins/optimize-css-assets.js | 1 + lib/plugins/shared-entry-concat.js | 1 + lib/plugins/terser.js | 1 + lib/plugins/variable-provider.js | 3 ++- lib/plugins/versioning.js | 1 + lib/plugins/vue.js | 1 + lib/utils/manifest-key-prefix-helper.js | 2 ++ 42 files changed, 66 insertions(+), 21 deletions(-) diff --git a/bin/encore.js b/bin/encore.js index 0e82b250..ee47aa53 100755 --- a/bin/encore.js +++ b/bin/encore.js @@ -12,7 +12,7 @@ const parseRuntime = require('../lib/config/parse-runtime'); const context = require('../lib/context'); -const chalk = require('chalk'); +const chalk = require('chalk').default; const logger = require('../lib/logger'); const runtimeConfig = parseRuntime( @@ -40,7 +40,7 @@ if (!runtimeConfig.isValidCommand) { } showUsageInstructions(); - process.exit(1); + process.exit(1); // eslint-disable-line no-process-exit } if (runtimeConfig.helpRequested) { diff --git a/index.js b/index.js index 458aeb95..be137723 100644 --- a/index.js +++ b/index.js @@ -9,6 +9,7 @@ 'use strict'; +const webpack = require('webpack'); // eslint-disable-line no-unused-vars const EncoreProxy = require('./lib/EncoreProxy'); const WebpackConfig = require('./lib/WebpackConfig'); const configGenerator = require('./lib/config-generator'); @@ -780,7 +781,7 @@ class Encore { * Cannot be used if you have an external Babel configuration (a .babelrc * file for instance). In this case you can set the option directly into * that configuration file. - * * {number|string} corejs (default=not set) + * * {number|string|object} corejs (default=not set) * Set the "corejs" option of @babel/preset-env. * It should contain the version of core-js you added to your project * if useBuiltIns isn't set to false. @@ -1193,7 +1194,7 @@ class Encore { * * module.exports = Encore.getWebpackConfig(); * - * @returns {*} + * @returns {webpack.Configuration} */ getWebpackConfig() { validator(webpackConfig); @@ -1255,6 +1256,13 @@ class Encore { return this; } + /** + * Check if Encore was either called through + * the CLI utility or after being manually intialized + * using Encore.configureRuntimeEnvironment. + * + * @returns {boolean} + */ isRuntimeEnvironmentConfigured() { return runtimeConfig !== null; } diff --git a/lib/EncoreProxy.js b/lib/EncoreProxy.js index 65dc0b23..acd26046 100644 --- a/lib/EncoreProxy.js +++ b/lib/EncoreProxy.js @@ -9,7 +9,7 @@ 'use strict'; -const chalk = require('chalk'); +const chalk = require('chalk').default; const levenshtein = require('fast-levenshtein'); const prettyError = require('./utils/pretty-error'); @@ -17,6 +17,12 @@ module.exports = { createProxy: (Encore) => { const EncoreProxy = new Proxy(Encore, { get: (target, prop) => { + if (typeof prop !== 'string') { + // Only care about strings there since prop + // could also be a number or a symbol + return target[prop]; + } + if (prop === '__esModule') { // When using Babel to preprocess a webpack.config.babel.js file // (for instance if we want to use ES6 syntax) the __esModule diff --git a/lib/WebpackConfig.js b/lib/WebpackConfig.js index 140f022a..0f28b487 100644 --- a/lib/WebpackConfig.js +++ b/lib/WebpackConfig.js @@ -12,10 +12,11 @@ const path = require('path'); const fs = require('fs'); const crypto = require('crypto'); +const RuntimeConfig = require('./config/RuntimeConfig'); //eslint-disable-line no-unused-vars const logger = require('./logger'); /** - * @param {RuntimeConfig} runtimeConfig + * @param {RuntimeConfig|null} runtimeConfig * @return {void} */ function validateRuntimeConfig(runtimeConfig) { @@ -41,7 +42,7 @@ function checkPackageJson(runtimeConfig) { // Display a warning if webpack is listed as a [dev-]dependency try { const packageInfo = JSON.parse( - fs.readFileSync(path.resolve(runtimeConfig.context, 'package.json')) + fs.readFileSync(path.resolve(runtimeConfig.context, 'package.json'), { encoding: 'utf-8' }) ); if (packageInfo) { diff --git a/lib/config-generator.js b/lib/config-generator.js index 64ec9127..af9d63f6 100644 --- a/lib/config-generator.js +++ b/lib/config-generator.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('./WebpackConfig'); //eslint-disable-line no-unused-vars const cssExtractLoaderUtil = require('./loaders/css-extract'); const pathUtil = require('./config/path-util'); const loaderFeatures = require('./features'); diff --git a/lib/config/RuntimeConfig.js b/lib/config/RuntimeConfig.js index 1d9bcfa9..945a5208 100644 --- a/lib/config/RuntimeConfig.js +++ b/lib/config/RuntimeConfig.js @@ -16,11 +16,13 @@ class RuntimeConfig { this.isValidCommand = false; this.environment = process.env.NODE_ENV ? process.env.NODE_ENV : 'dev'; - this.useDevServer = null; + this.useDevServer = false; this.devServerUrl = null; this.devServerHttps = null; this.devServerKeepPublicPath = false; - this.useHotModuleReplacement = null; + this.useHotModuleReplacement = false; + this.outputJson = false; + this.profile = false; this.babelRcFileExists = null; diff --git a/lib/config/parse-runtime.js b/lib/config/parse-runtime.js index 78bf2f05..34f726d6 100644 --- a/lib/config/parse-runtime.js +++ b/lib/config/parse-runtime.js @@ -22,10 +22,6 @@ const babel = require('@babel/core'); module.exports = function(argv, cwd) { const runtimeConfig = new RuntimeConfig(); runtimeConfig.command = argv._[0]; - runtimeConfig.useDevServer = false; - runtimeConfig.useHotModuleReplacement = false; - runtimeConfig.outputJson = false; - runtimeConfig.profile = false; switch (runtimeConfig.command) { case 'dev': diff --git a/lib/config/path-util.js b/lib/config/path-util.js index bbafefa4..d3831a7d 100644 --- a/lib/config/path-util.js +++ b/lib/config/path-util.js @@ -10,6 +10,7 @@ 'use strict'; const path = require('path'); +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars module.exports = { /** diff --git a/lib/config/validator.js b/lib/config/validator.js index ca5c5141..bb8d0fd8 100644 --- a/lib/config/validator.js +++ b/lib/config/validator.js @@ -11,6 +11,7 @@ const pathUtil = require('./path-util'); const logger = require('./../logger'); +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars class Validator { /** diff --git a/lib/friendly-errors/asset-output-display-plugin.js b/lib/friendly-errors/asset-output-display-plugin.js index b4c70562..66c1449f 100644 --- a/lib/friendly-errors/asset-output-display-plugin.js +++ b/lib/friendly-errors/asset-output-display-plugin.js @@ -9,7 +9,7 @@ 'use strict'; -const chalk = require('chalk'); +const chalk = require('chalk').default; function AssetOutputDisplayPlugin(outputPath, friendlyErrorsPlugin) { this.outputPath = outputPath; diff --git a/lib/friendly-errors/formatters/missing-css-file.js b/lib/friendly-errors/formatters/missing-css-file.js index d5bf67ee..e0533455 100644 --- a/lib/friendly-errors/formatters/missing-css-file.js +++ b/lib/friendly-errors/formatters/missing-css-file.js @@ -9,7 +9,7 @@ 'use strict'; -const chalk = require('chalk'); +const chalk = require('chalk').default; function formatErrors(errors) { if (errors.length === 0) { diff --git a/lib/friendly-errors/formatters/missing-loader.js b/lib/friendly-errors/formatters/missing-loader.js index 746763e9..1343f746 100644 --- a/lib/friendly-errors/formatters/missing-loader.js +++ b/lib/friendly-errors/formatters/missing-loader.js @@ -9,7 +9,7 @@ 'use strict'; -const chalk = require('chalk'); +const chalk = require('chalk').default; const loaderFeatures = require('../../features'); function formatErrors(errors) { diff --git a/lib/friendly-errors/formatters/missing-postcss-config.js b/lib/friendly-errors/formatters/missing-postcss-config.js index ffe5de00..feb82301 100644 --- a/lib/friendly-errors/formatters/missing-postcss-config.js +++ b/lib/friendly-errors/formatters/missing-postcss-config.js @@ -9,7 +9,7 @@ 'use strict'; -const chalk = require('chalk'); +const chalk = require('chalk').default; function formatErrors(errors) { if (errors.length === 0) { diff --git a/lib/loaders/babel.js b/lib/loaders/babel.js index 4e7240a7..e01481c5 100644 --- a/lib/loaders/babel.js +++ b/lib/loaders/babel.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const loaderFeatures = require('../features'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/loaders/css-extract.js b/lib/loaders/css-extract.js index a718bb66..bbd83304 100644 --- a/lib/loaders/css-extract.js +++ b/lib/loaders/css-extract.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { diff --git a/lib/loaders/css.js b/lib/loaders/css.js index e38e004e..03f06c5e 100644 --- a/lib/loaders/css.js +++ b/lib/loaders/css.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const loaderFeatures = require('../features'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/loaders/eslint.js b/lib/loaders/eslint.js index f3811153..f1e6f8cf 100644 --- a/lib/loaders/eslint.js +++ b/lib/loaders/eslint.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const loaderFeatures = require('../features'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/loaders/handlebars.js b/lib/loaders/handlebars.js index 95731ce9..749b35c2 100644 --- a/lib/loaders/handlebars.js +++ b/lib/loaders/handlebars.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const loaderFeatures = require('../features'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/loaders/less.js b/lib/loaders/less.js index 753f3045..e6edb8de 100644 --- a/lib/loaders/less.js +++ b/lib/loaders/less.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const loaderFeatures = require('../features'); const cssLoader = require('./css'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/loaders/sass.js b/lib/loaders/sass.js index 6d3ec9de..3b0e23ae 100644 --- a/lib/loaders/sass.js +++ b/lib/loaders/sass.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const loaderFeatures = require('../features'); const cssLoader = require('./css'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/loaders/stylus.js b/lib/loaders/stylus.js index 7aaa7084..06fd70b8 100644 --- a/lib/loaders/stylus.js +++ b/lib/loaders/stylus.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const loaderFeatures = require('../features'); const cssLoader = require('./css'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/loaders/typescript.js b/lib/loaders/typescript.js index 68d4accc..18cccb50 100644 --- a/lib/loaders/typescript.js +++ b/lib/loaders/typescript.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const loaderFeatures = require('../features'); const babelLoader = require('./babel'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/loaders/vue.js b/lib/loaders/vue.js index 1c8a851d..45bc120f 100644 --- a/lib/loaders/vue.js +++ b/lib/loaders/vue.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const loaderFeatures = require('../features'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/logger.js b/lib/logger.js index 14877dfe..edc38d2f 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -9,7 +9,7 @@ 'use strict'; -const chalk = require('chalk'); +const chalk = require('chalk').default; const messagesKeys = [ 'debug', diff --git a/lib/package-helper.js b/lib/package-helper.js index 56f52830..81fd432c 100644 --- a/lib/package-helper.js +++ b/lib/package-helper.js @@ -9,7 +9,7 @@ 'use strict'; -const chalk = require('chalk'); +const chalk = require('chalk').default; const fs = require('fs'); const logger = require('./logger'); const semver = require('semver'); @@ -25,7 +25,7 @@ ${missingPackagesRecommendation.message} } // check for invalid versions & warn - const invalidVersionRecommendations = getInvalidPackageVersionRecommendations(packagesConfig, requestedFeature); + const invalidVersionRecommendations = getInvalidPackageVersionRecommendations(packagesConfig); for (let message of invalidVersionRecommendations) { logger.warning(message); } diff --git a/lib/plugins/asset-output-display.js b/lib/plugins/asset-output-display.js index 7b3bd129..c774166b 100644 --- a/lib/plugins/asset-output-display.js +++ b/lib/plugins/asset-output-display.js @@ -9,6 +9,8 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars +const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin'); //eslint-disable-line no-unused-vars const pathUtil = require('../config/path-util'); const AssetOutputDisplayPlugin = require('../friendly-errors/asset-output-display-plugin'); const PluginPriorities = require('./plugin-priorities'); diff --git a/lib/plugins/clean.js b/lib/plugins/clean.js index 5cbb0258..f07f7cd6 100644 --- a/lib/plugins/clean.js +++ b/lib/plugins/clean.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const CleanWebpackPlugin = require('clean-webpack-plugin'); const PluginPriorities = require('./plugin-priorities'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/plugins/define.js b/lib/plugins/define.js index b18ce878..9fcfff90 100644 --- a/lib/plugins/define.js +++ b/lib/plugins/define.js @@ -10,6 +10,7 @@ 'use strict'; const webpack = require('webpack'); +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const PluginPriorities = require('./plugin-priorities'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/plugins/delete-unused-entries.js b/lib/plugins/delete-unused-entries.js index f2aa3516..0801617b 100644 --- a/lib/plugins/delete-unused-entries.js +++ b/lib/plugins/delete-unused-entries.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const DeleteUnusedEntriesJSPlugin = require('../webpack/delete-unused-entries-js-plugin'); const PluginPriorities = require('./plugin-priorities'); const copyEntryTmpName = require('../utils/copyEntryTmpName'); diff --git a/lib/plugins/entry-files-manifest.js b/lib/plugins/entry-files-manifest.js index a4b47fc3..6998878c 100644 --- a/lib/plugins/entry-files-manifest.js +++ b/lib/plugins/entry-files-manifest.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const PluginPriorities = require('./plugin-priorities'); const sharedEntryTmpName = require('../utils/sharedEntryTmpName'); const copyEntryTmpName = require('../utils/copyEntryTmpName'); diff --git a/lib/plugins/forked-ts-types.js b/lib/plugins/forked-ts-types.js index ae002da7..7930bc9a 100644 --- a/lib/plugins/forked-ts-types.js +++ b/lib/plugins/forked-ts-types.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); // eslint-disable-line const PluginPriorities = require('./plugin-priorities'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/plugins/friendly-errors.js b/lib/plugins/friendly-errors.js index cc6a2bde..729038d0 100644 --- a/lib/plugins/friendly-errors.js +++ b/lib/plugins/friendly-errors.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin'); const missingCssFileTransformer = require('../friendly-errors/transformers/missing-css-file'); const missingCssFileFormatter = require('../friendly-errors/formatters/missing-css-file'); diff --git a/lib/plugins/manifest.js b/lib/plugins/manifest.js index 0c864784..b8465ba4 100644 --- a/lib/plugins/manifest.js +++ b/lib/plugins/manifest.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const ManifestPlugin = require('webpack-manifest-plugin'); const PluginPriorities = require('./plugin-priorities'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/plugins/mini-css-extract.js b/lib/plugins/mini-css-extract.js index f987fa4d..68193323 100644 --- a/lib/plugins/mini-css-extract.js +++ b/lib/plugins/mini-css-extract.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const PluginPriorities = require('./plugin-priorities'); diff --git a/lib/plugins/notifier.js b/lib/plugins/notifier.js index f409a63e..63afc3d9 100644 --- a/lib/plugins/notifier.js +++ b/lib/plugins/notifier.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const pluginFeatures = require('../features'); const PluginPriorities = require('./plugin-priorities'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/plugins/optimize-css-assets.js b/lib/plugins/optimize-css-assets.js index daeda6d6..b10c2f1b 100644 --- a/lib/plugins/optimize-css-assets.js +++ b/lib/plugins/optimize-css-assets.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/plugins/shared-entry-concat.js b/lib/plugins/shared-entry-concat.js index ce1e9f42..2cced182 100644 --- a/lib/plugins/shared-entry-concat.js +++ b/lib/plugins/shared-entry-concat.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const SharedEntryConcatPlugin = require('../webpack/shared-entry-concat-plugin'); const PluginPriorities = require('./plugin-priorities'); diff --git a/lib/plugins/terser.js b/lib/plugins/terser.js index 51365be1..dac446d6 100644 --- a/lib/plugins/terser.js +++ b/lib/plugins/terser.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const TerserPlugin = require('terser-webpack-plugin'); const applyOptionsCallback = require('../utils/apply-options-callback'); diff --git a/lib/plugins/variable-provider.js b/lib/plugins/variable-provider.js index 2e86d698..bf30432b 100644 --- a/lib/plugins/variable-provider.js +++ b/lib/plugins/variable-provider.js @@ -9,13 +9,14 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const webpack = require('webpack'); const PluginPriorities = require('./plugin-priorities'); /** * @param {Array} plugins * @param {WebpackConfig} webpackConfig - * @return {Array} of plugins to add to webpack + * @return {void} */ module.exports = function(plugins, webpackConfig) { if (Object.keys(webpackConfig.providedVariables).length > 0) { diff --git a/lib/plugins/versioning.js b/lib/plugins/versioning.js index aed474e9..5ae6b58c 100644 --- a/lib/plugins/versioning.js +++ b/lib/plugins/versioning.js @@ -11,6 +11,7 @@ const webpack = require('webpack'); const WebpackChunkHash = require('webpack-chunk-hash'); +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const PluginPriorities = require('./plugin-priorities'); /** diff --git a/lib/plugins/vue.js b/lib/plugins/vue.js index b34914eb..5e1aa37c 100644 --- a/lib/plugins/vue.js +++ b/lib/plugins/vue.js @@ -9,6 +9,7 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars const PluginPriorities = require('./plugin-priorities'); /** diff --git a/lib/utils/manifest-key-prefix-helper.js b/lib/utils/manifest-key-prefix-helper.js index 77138610..44b83082 100644 --- a/lib/utils/manifest-key-prefix-helper.js +++ b/lib/utils/manifest-key-prefix-helper.js @@ -9,6 +9,8 @@ 'use strict'; +const WebpackConfig = require('../WebpackConfig'); //eslint-disable-line no-unused-vars + /** * Helper for determining the manifest.json key prefix. * From b2474fc0b72481b54594fccb9120690681788c13 Mon Sep 17 00:00:00 2001 From: Lyrkan <850046+Lyrkan@users.noreply.github.com> Date: Sun, 31 Mar 2019 04:48:56 +0200 Subject: [PATCH 4/5] Add code blocks to the public API's comments --- index.js | 548 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 325 insertions(+), 223 deletions(-) diff --git a/index.js b/index.js index be137723..68b963fc 100644 --- a/index.js +++ b/index.js @@ -40,16 +40,24 @@ class Encore { * The public version of outputPath: the public path to outputPath. * * For example, if "web" is your document root, then: - * .setOutputPath('web/build') - * .setPublicPath('/build') + * + * ``` + * Encore + * .setOutputPath('web/build') + * .setPublicPath('/build') + * ``` * * This can also be set to an absolute URL if you're using * a CDN: publicPath is used as the prefix to all asset paths * in the manifest.json file and internally in webpack: - * .setOutputPath('web/build') - * .setPublicPath('https://coolcdn.com') - * // needed when public path is absolute - * .setManifestKeyPrefix('/build') + * + * ``` + * Encore + * .setOutputPath('web/build') + * .setPublicPath('https://coolcdn.com') + * // needed when public path is absolute + * .setManifestKeyPrefix('/build') + * ``` * * @param {string} publicPath * @returns {Encore} @@ -70,15 +78,20 @@ class Encore { * But if publicPath is absolute, then we require you to set this. * For example: * - * .setOutputPath('web/build') - * .setPublicPath('https://coolcdn.com/FOO') - * .setManifestKeyPrefix('build/') + * ``` + * Encore + * .setOutputPath('web/build') + * .setPublicPath('https://coolcdn.com/FOO') + * .setManifestKeyPrefix('build/') + * ``` * * The manifest.json file would look something like this: * - * { - * "build/main.js": "https://coolcdn.com/FOO/main.a54f3ccd2.js" - * } + * ``` + * { + * "build/main.js": "https://coolcdn.com/FOO/main.a54f3ccd2.js" + * } + * ``` * * @param {string} manifestKeyPrefix * @returns {Encore} @@ -95,9 +108,11 @@ class Encore { * * For example: * - * Encore.configureDefinePlugin((options) => { - * options.VERSION = JSON.stringify('1.0.0'); - * }) + * ``` + * Encore.configureDefinePlugin((options) => { + * options.VERSION = JSON.stringify('1.0.0'); + * }) + * ``` * * @param {function} definePluginOptionsCallback * @returns {Encore} @@ -114,9 +129,11 @@ class Encore { * * For example: * - * Encore.configureFriendlyErrorsPlugin((options) => { - * options.clearConsole = true; - * }) + * ``` + * Encore.configureFriendlyErrorsPlugin((options) => { + * options.clearConsole = true; + * }) + * ``` * * @param {function} friendlyErrorsPluginOptionsCallback * @returns {Encore} @@ -133,9 +150,11 @@ class Encore { * * For example: * - * Encore.configureManifestPlugin((options) => { - * options.fileName = '../../var/assets/manifest.json'; - * }) + * ``` + * Encore.configureManifestPlugin((options) => { + * options.fileName = '../../var/assets/manifest.json'; + * }) + * ``` * * @param {function} manifestPluginOptionsCallback * @returns {Encore} @@ -152,14 +171,16 @@ class Encore { * * For example: * - * Encore.configureTerserPlugin((options) => { - * options.cache = true; - * options.terserOptions = { - * output: { - * comments: false - * } - * } - * }) + * ``` + * Encore.configureTerserPlugin((options) => { + * options.cache = true; + * options.terserOptions = { + * output: { + * comments: false + * } + * } + * }) + * ``` * * @param {function} terserPluginOptionsCallback * @returns {Encore} @@ -176,12 +197,14 @@ class Encore { * * For example: * - * Encore.configureOptimizeCssPlugin((options) => { - * options.cssProcessor = require('cssnano'); - * options.cssProcessorPluginOptions = { - * preset: ['default', { discardComments: { removeAll: true } }], - * } - * }) + * ``` + * Encore.configureOptimizeCssPlugin((options) => { + * options.cssProcessor = require('cssnano'); + * options.cssProcessorPluginOptions = { + * preset: ['default', { discardComments: { removeAll: true } }], + * } + * }) + * ``` * * @param {function} optimizeCssPluginOptionsCallback * @returns {Encore} @@ -195,8 +218,10 @@ class Encore { /** * Adds a JavaScript file that should be webpacked: * - * // final output file will be main.js in the output directory - * Encore.addEntry('main', './path/to/some_file.js'); + * ``` + * // final output file will be main.js in the output directory + * Encore.addEntry('main', './path/to/some_file.js'); + * ``` * * If the JavaScript file imports/requires CSS/Sass/LESS files, * then a CSS file (e.g. main.css) will also be output. @@ -216,8 +241,10 @@ class Encore { /** * Adds a CSS/SASS/LESS file that should be webpacked: * - * // final output file will be main.css in the output directory - * Encore.addEntry('main', './path/to/some_file.css'); + * ``` + * // final output file will be main.css in the output directory + * Encore.addEntry('main', './path/to/some_file.css'); + * ``` * * This is actually not something Webpack does natively, and you * should avoid using this function when possible. A better option @@ -240,7 +267,10 @@ class Encore { * Add a plugin to the sets of plugins already registered by Encore * * For example, if you want to add the "webpack.IgnorePlugin()", then: - * .addPlugin(new webpack.IgnorePlugin(requestRegExp, contextRegExp)) + * + * ``` + * Encore.addPlugin(new webpack.IgnorePlugin(requestRegExp, contextRegExp)) + * ``` * * By default custom plugins are added after the ones managed by Encore * but you can also set a priority to define where your plugin will be @@ -249,7 +279,9 @@ class Encore { * For example, if a plugin has a priority of 0 and you want to add * another plugin after it, then: * - * .addPlugin(new MyWebpackPlugin(), -10) + * ``` + * Encore.addPlugin(new MyWebpackPlugin(), -10) + * ``` * * The priority of each plugin added by Encore can be found in the * "lib/plugins/plugin-priorities.js" file. It is recommended to use @@ -260,10 +292,12 @@ class Encore { * For example, if you want one of your plugins to have the same priority * than the DefinePlugin: * - * const Encore = require('@symfony/webpack-encore'); - * const PluginPriorities = require('@symfony/webpack-encore/lib/plugins/plugin-priorities.js'); + * ``` + * const Encore = require('@symfony/webpack-encore'); + * const PluginPriorities = require('@symfony/webpack-encore/lib/plugins/plugin-priorities.js'); * - * Encore.addPlugin(new MyWebpackPlugin(), PluginPriorities.DefinePlugin); + * Encore.addPlugin(new MyWebpackPlugin(), PluginPriorities.DefinePlugin); + * ``` * * @param {object} plugin * @param {number} priority @@ -309,10 +343,12 @@ class Encore { * * For example: * - * Encore.addAliases({ - * Utilities: path.resolve(__dirname, 'src/utilities/'), - * Templates: path.resolve(__dirname, 'src/templates/') - * }) + * ``` + * Encore.addAliases({ + * Utilities: path.resolve(__dirname, 'src/utilities/'), + * Templates: path.resolve(__dirname, 'src/templates/') + * }) + * ``` * * @param {object} aliases * @@ -331,24 +367,28 @@ class Encore { * * For example: * - * Encore.addExternals({ - * jquery: 'jQuery', - * react: 'react' - * }); + * ``` + * Encore.addExternals({ + * jquery: 'jQuery', + * react: 'react' + * }); + * ``` * * Or: * - * const nodeExternals = require('webpack-node-externals'); + * ``` + * const nodeExternals = require('webpack-node-externals'); * - * Encore.addExternals( - * nodeExternals() - * ); + * Encore.addExternals( + * nodeExternals() + * ); * - * // or add multiple things at once - * Encore.addExternals([ - * nodeExternals(), - * /^(jquery|\$)$/i - * ]); + * // or add multiple things at once + * Encore.addExternals([ + * nodeExternals(), + * /^(jquery|\$)$/i + * ]); + * ``` * * @param {*} externals * @@ -411,39 +451,41 @@ class Encore { * * For example: * - * // Copy the content of a whole directory and its subdirectories - * Encore.copyFiles({ from: './assets/images' }); - * - * // Only copy files matching a given pattern - * Encore.copyFiles({ from: './assets/images', pattern: /\.(png|jpg|jpeg)$/ }) - * - * // Set the path the files are copied to - * Encore.copyFiles({ - * from: './assets/images', - * pattern: /\.(png|jpg|jpeg)$/, - * // to path is relative to the build directory - * to: 'images/[path][name].[ext]' - * }) - * - * // Version files - * Encore.copyFiles({ - * from: './assets/images', - * to: 'images/[path][name].[hash:8].[ext]' - * }) - * - * // Add multiple configs in a single call - * Encore.copyFiles([ - * { from: './assets/images' }, - * { from: './txt', pattern: /\.txt$/ }, - * ]); - * - * // Set the context path: files will be copied - * // into an images/ directory in the output dir - * Encore.copyFiles({ - * from: './assets/images', - * to: '[path][name].[hash:8].[ext]', - * context: './assets' - * }); + * ``` + * // Copy the content of a whole directory and its subdirectories + * Encore.copyFiles({ from: './assets/images' }); + * + * // Only copy files matching a given pattern + * Encore.copyFiles({ from: './assets/images', pattern: /\.(png|jpg|jpeg)$/ }) + * + * // Set the path the files are copied to + * Encore.copyFiles({ + * from: './assets/images', + * pattern: /\.(png|jpg|jpeg)$/, + * // to path is relative to the build directory + * to: 'images/[path][name].[ext]' + * }) + * + * // Version files + * Encore.copyFiles({ + * from: './assets/images', + * to: 'images/[path][name].[hash:8].[ext]' + * }) + * + * // Add multiple configs in a single call + * Encore.copyFiles([ + * { from: './assets/images' }, + * { from: './txt', pattern: /\.txt$/ }, + * ]); + * + * // Set the context path: files will be copied + * // into an images/ directory in the output dir + * Encore.copyFiles({ + * from: './assets/images', + * to: '[path][name].[hash:8].[ext]', + * context: './assets' + * }); + * ``` * * Notes: * * No transformation is applied to the copied files (for instance @@ -542,11 +584,12 @@ class Encore { * * https://webpack.js.org/plugins/split-chunks-plugin/ * + * ``` * Encore.configureSplitChunks(function(splitChunks) { - * // change the configuration - * - * splitChunks.minSize = 0; + * // change the configuration + * splitChunks.minSize = 0; * }); + * ``` * * @param {function} callback * @returns {Encore} @@ -563,11 +606,12 @@ class Encore { * https://webpack.js.org/configuration/watch/ * https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- * + * ``` * Encore.configureWatchOptions(function(watchOptions) { - * // change the configuration - * - * watchOptions.poll = 250; // useful when running inside a Virtual Machine + * // change the configuration + * watchOptions.poll = 250; // useful when running inside a Virtual Machine * }); + * ``` * * @param {function} callback * @returns {Encore} @@ -583,10 +627,12 @@ class Encore { * * Usage: * - * WebpackConfig.autoProvideVariables({ - * $: 'jquery', - * jQuery: 'jquery' - * }); + * ``` + * WebpackConfig.autoProvideVariables({ + * $: 'jquery', + * jQuery: 'jquery' + * }); + * ``` * * Then, whenever $ or jQuery are found in any * modules, webpack will automatically require @@ -607,10 +653,12 @@ class Encore { /** * Makes jQuery available everywhere. Equivalent to * - * WebpackConfig.autoProvideVariables({ - * $: 'jquery', - * jQuery: 'jquery' - * }); + * ``` + * WebpackConfig.autoProvideVariables({ + * $: 'jquery', + * jQuery: 'jquery' + * }); + * ``` * * @returns {Encore} */ @@ -627,14 +675,18 @@ class Encore { * * https://github.com/postcss/postcss-loader * - * Encore.enablePostCssLoader(); + * ``` + * Encore.enablePostCssLoader(); + * ``` * * Or pass options to the loader * - * Encore.enablePostCssLoader(function(options) { - * // https://github.com/postcss/postcss-loader#options - * // options.config = {...} - * }) + * ``` + * Encore.enablePostCssLoader(function(options) { + * // https://github.com/postcss/postcss-loader#options + * // options.config = {...} + * }) + * ``` * * @param {function} postCssLoaderOptionsCallback * @returns {Encore} @@ -648,17 +700,21 @@ class Encore { /** * Call this if you plan on loading SASS files. * - * Encore.enableSassLoader(); + * ``` + * Encore.enableSassLoader(); + * ``` * * Or pass options to node-sass * - * Encore.enableSassLoader(function(options) { - * // https://github.com/sass/node-sass#options - * // options.includePaths = [...] - * }, { - * // set optional Encore-specific options - * // resolveUrlLoader: true - * }); + * ``` + * Encore.enableSassLoader(function(options) { + * // https://github.com/sass/node-sass#options + * // options.includePaths = [...] + * }, { + * // set optional Encore-specific options + * // resolveUrlLoader: true + * }); + * ``` * * Supported options: * * {boolean} resolveUrlLoader (default=true) @@ -682,15 +738,19 @@ class Encore { /** * Call this if you plan on loading less files. * - * Encore.enableLessLoader(); + * ``` + * Encore.enableLessLoader(); + * ``` * * Or pass options to the loader * - * Encore.enableLessLoader(function(options) { - * // https://github.com/webpack-contrib/less-loader#examples - * // http://lesscss.org/usage/#command-line-usage-options - * // options.relativeUrls = false; - * }); + * ``` + * Encore.enableLessLoader(function(options) { + * // https://github.com/webpack-contrib/less-loader#examples + * // http://lesscss.org/usage/#command-line-usage-options + * // options.relativeUrls = false; + * }); + * ``` * * @param {function} lessLoaderOptionsCallback * @returns {Encore} @@ -704,14 +764,18 @@ class Encore { /** * Call this if you plan on loading stylus files. * - * Encore.enableStylusLoader(); + * ``` + * Encore.enableStylusLoader(); + * ``` * * Or pass options to the loader * - * Encore.enableStylusLoader(function(options) { - * // https://github.com/shama/stylus-loader - * // options.import = ['~library/index.styl']; - * }); + * ``` + * Encore.enableStylusLoader(function(options) { + * // https://github.com/shama/stylus-loader + * // options.import = ['~library/index.styl']; + * }); + * ``` * * @param {function} stylusLoaderOptionsCallback * @returns {Encore} @@ -727,33 +791,35 @@ class Encore { * * https://babeljs.io/docs/usage/babelrc/ * + * ``` * Encore.configureBabel(function(babelConfig) { - * // change the babelConfig - * // if you use an external Babel configuration - * // this callback will NOT be used. In this case - * // you can pass null as the first parameter to - * // still be able to use some of the options below - * // without a warning. + * // change the babelConfig + * // if you use an external Babel configuration + * // this callback will NOT be used. In this case + * // you can pass null as the first parameter to + * // still be able to use some of the options below + * // without a warning. * }, { - * // set optional Encore-specific options, for instance: + * // set optional Encore-specific options, for instance: * - * // change the rule that determines which files - * // won't be processed by Babel - * exclude: /bower_components/ + * // change the rule that determines which files + * // won't be processed by Babel + * exclude: /bower_components/ * - * // ...or keep the default rule but only allow - * // *some* Node modules to be processed by Babel - * includeNodeModules: ['foundation-sites'] + * // ...or keep the default rule but only allow + * // *some* Node modules to be processed by Babel + * includeNodeModules: ['foundation-sites'] * - * // automatically import polyfills where they - * // are needed - * useBuiltIns: 'usage' + * // automatically import polyfills where they + * // are needed + * useBuiltIns: 'usage' * - * // if you set useBuiltIns you also have to add - * // core-js to your project using Yarn or npm and - * // inform Babel of the version it will use. - * corejs: 3 + * // if you set useBuiltIns you also have to add + * // core-js to your project using Yarn or npm and + * // inform Babel of the version it will use. + * corejs: 3 * }); + * ``` * * Supported options: * * {Condition} exclude (default=/(node_modules|bower_components)/) @@ -801,10 +867,12 @@ class Encore { * * https://github.com/webpack-contrib/css-loader#options * + * ``` * Encore.configureCssLoader(function(config) { - * // change the config - * // config.minimize = true; + * // change the config + * // config.minimize = true; * }); + * ``` * * @param {function} callback * @returns {Encore} @@ -832,12 +900,16 @@ class Encore { * If enabled, a Preact preset will be applied to * the generated Webpack configuration. * - * Encore.enablePreactPreset() + * ``` + * Encore.enablePreactPreset() + * ``` * * If you wish to also use preact-compat (https://github.com/developit/preact-compat) * you can enable it by setting the "preactCompat" option to true: * - * Encore.enablePreactPreset({ preactCompat: true }) + * ``` + * Encore.enablePreactPreset({ preactCompat: true }) + * ``` * * @param {object} options * @returns {Encore} @@ -851,14 +923,18 @@ class Encore { /** * Call this if you plan on loading TypeScript files. * + * ``` * Encore.enableTypeScriptLoader() + * ``` * * Or, configure the ts-loader options: * + * ``` * Encore.enableTypeScriptLoader(function(tsConfig) { - * // https://github.com/TypeStrong/ts-loader/blob/master/README.md#loader-options - * // tsConfig.silent = false; + * // https://github.com/TypeStrong/ts-loader/blob/master/README.md#loader-options + * // tsConfig.silent = false; * }); + * ``` * * @param {function} callback * @returns {Encore} @@ -891,13 +967,15 @@ class Encore { * * https://github.com/vuejs/vue-loader * - * Encore.enableVueLoader(); + * ``` + * Encore.enableVueLoader(); * - * // or configure the vue-loader options - * // https://vue-loader.vuejs.org/en/configurations/advanced.html - * Encore.enableVueLoader(function(options) { - * options.preLoaders = { ... } - * }); + * // or configure the vue-loader options + * // https://vue-loader.vuejs.org/en/configurations/advanced.html + * Encore.enableVueLoader(function(options) { + * options.preLoaders = { ... } + * }); + * ``` * * @param {function} vueLoaderOptionsCallback * @returns {Encore} @@ -913,25 +991,27 @@ class Encore { * * https://github.com/MoOx/eslint-loader * - * // enables the eslint loaded using the default eslint configuration. - * Encore.enableEslintLoader(); + * ``` + * // enables the eslint loaded using the default eslint configuration. + * Encore.enableEslintLoader(); * - * // Optionally, you can pass in the configuration eslint should extend. - * Encore.enableEslintLoader('airbnb'); + * // Optionally, you can pass in the configuration eslint should extend. + * Encore.enableEslintLoader('airbnb'); * - * // You can also pass in an object of options - * // that will be passed on to the eslint-loader - * Encore.enableEslintLoader({ - * extends: 'airbnb', - emitWarning: false - * }); + * // You can also pass in an object of options + * // that will be passed on to the eslint-loader + * Encore.enableEslintLoader({ + * extends: 'airbnb', + * emitWarning: false + * }); * - * // For a more advanced usage you can pass in a callback - * // https://github.com/MoOx/eslint-loader#options - * Encore.enableEslintLoader((options) => { - * options.extends = 'airbnb'; - * options.emitWarning = false; - * }); + * // For a more advanced usage you can pass in a callback + * // https://github.com/MoOx/eslint-loader#options + * Encore.enableEslintLoader((options) => { + * options.extends = 'airbnb'; + * options.emitWarning = false; + * }); + * ``` * * @param {string|object|function} eslintLoaderOptionsOrCallback * @returns {Encore} @@ -948,13 +1028,15 @@ class Encore { * * https://github.com/Turbo87/webpack-notifier * - * Encore.enableBuildNotifications(); + * ``` + * Encore.enableBuildNotifications(); * - * // or configure the webpack-notifier options - * // https://github.com/Turbo87/webpack-notifier#configuration - * Encore.enableBuildNotifications(true, function(options) { - * options.title = 'Webpack build'; - * }); + * // or configure the webpack-notifier options + * // https://github.com/Turbo87/webpack-notifier#configuration + * Encore.enableBuildNotifications(true, function(options) { + * options.title = 'Webpack build'; + * }); + * ``` * * @param {boolean} enabled * @param {function} notifierPluginOptionsCallback @@ -969,14 +1051,18 @@ class Encore { /** * Call this if you plan on loading Handlebars files. * - * Encore.enableHandlebarsLoader(); + * ``` + * Encore.enableHandlebarsLoader(); + * ``` * * Or pass options to the loader * - * Encore.enableHandlebarsLoader(function(options) { - * // https://github.com/pcardune/handlebars-loader - * // options.debug = true; - * }); + * ``` + * Encore.enableHandlebarsLoader(function(options) { + * // https://github.com/pcardune/handlebars-loader + * // options.debug = true; + * }); + * ``` * * @param {function} callback * @returns {Encore} @@ -1031,12 +1117,14 @@ class Encore { * Call this to change how the name of each output * file is generated. * - * Encore.configureFilenames({ - * js: '[name].[contenthash].js', - * css: '[name].[contenthash].css', - * images: 'images/[name].[hash:8].[ext]', - * fonts: 'fonts/[name].[hash:8].[ext]' - * }); + * ``` + * Encore.configureFilenames({ + * js: '[name].[contenthash].js', + * css: '[name].[contenthash].css', + * images: 'images/[name].[hash:8].[ext]', + * fonts: 'fonts/[name].[hash:8].[ext]' + * }); + * ``` * * It's safe to omit a key (e.g. css): the default naming strategy * will be used for any file types not passed. @@ -1059,15 +1147,17 @@ class Encore { * * https://github.com/webpack-contrib/url-loader * - * Encore.configureUrlLoader({ - * images: { - * limit: 8192, - * mimetype: 'image/png' - * }, - * fonts: { - * limit: 4096 - * } - * }); + * ``` + * Encore.configureUrlLoader({ + * images: { + * limit: 8192, + * mimetype: 'image/png' + * }, + * fonts: { + * limit: 4096 + * } + * }); + * ``` * * If a key (e.g. fonts) doesn't exists or contains a * falsy value the file-loader will be used instead. @@ -1090,12 +1180,14 @@ class Encore { * For example, if you are using Vue and ESLint loader, * this is how you can configure ESLint to lint Vue files: * - * Encore - * .enableEslintLoader() - * .enableVueLoader() - * .configureLoaderRule('eslint', (loaderRule) => { - * loaderRule.test = /\.(jsx?|vue)/; - * }); + * ``` + * Encore + * .enableEslintLoader() + * .enableVueLoader() + * .configureLoaderRule('eslint', (loaderRule) => { + * loaderRule.test = /\.(jsx?|vue)/; + * }); + * ``` * * @param {string} name * @param {function} callback @@ -1114,9 +1206,11 @@ class Encore { * * For example: * - * Encore.cleanupOutputBeforeBuild(['*.js'], (options) => { - * options.dry = true; - * }) + * ``` + * Encore.cleanupOutputBeforeBuild(['*.js'], (options) => { + * options.dry = true; + * }) + * ``` * * @param {Array} paths Paths that should be cleaned, relative to the "root" option * @param {function} cleanWebpackPluginOptionsCallback @@ -1140,17 +1234,21 @@ class Encore { * * For example: * - * Encore.enableIntegrityHashes( - * Encore.isProduction(), - * 'sha384' - * ); + * ``` + * Encore.enableIntegrityHashes( + * Encore.isProduction(), + * 'sha384' + * ); + * ``` * * Or with multiple algorithms: * - * Encore.enableIntegrityHashes( - * Encore.isProduction(), - * ['sha256', 'sha384', 'sha512'] - * ); + * ``` + * Encore.enableIntegrityHashes( + * Encore.isProduction(), + * ['sha256', 'sha384', 'sha512'] + * ); + * ``` * * @param {boolean} enabled * @param {string|Array} algorithms @@ -1192,7 +1290,9 @@ class Encore { /** * Use this at the bottom of your webpack.config.js file: * + * ``` * module.exports = Encore.getWebpackConfig(); + * ``` * * @returns {webpack.Configuration} */ @@ -1221,6 +1321,7 @@ class Encore { * using Encore without executing the "./node_module/.bin/encore" * utility (e.g. with karma-webpack). * + * ``` * Encore.configureRuntimeEnvironment( * // Environment to use (dev, dev-server, production) * 'dev-server', @@ -1233,6 +1334,7 @@ class Encore { * keepPublicPath: true * } * ) + * ``` * * Be aware than using this method will also reset the current * webpack configuration. From 1274908c10d69f1b19e099b8d21ba46dadf796b7 Mon Sep 17 00:00:00 2001 From: Lyrkan <850046+Lyrkan@users.noreply.github.com> Date: Sun, 31 Mar 2019 14:40:32 +0200 Subject: [PATCH 5/5] Add some comments to the public API --- index.js | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 68b963fc..8f8796e5 100644 --- a/index.js +++ b/index.js @@ -219,8 +219,8 @@ class Encore { * Adds a JavaScript file that should be webpacked: * * ``` - * // final output file will be main.js in the output directory - * Encore.addEntry('main', './path/to/some_file.js'); + * // final output file will be main.js in the output directory + * Encore.addEntry('main', './path/to/some_file.js'); * ``` * * If the JavaScript file imports/requires CSS/Sass/LESS files, @@ -408,6 +408,15 @@ class Encore { * directory with a map from the original file path to * the versioned path (e.g. `builds/main.js` => `builds/main.a2b61cc.js`) * + * Note that the versioning must be disabled if you + * want to use the dev-server. + * + * For example: + * + * ``` + * Encore.enableVersioning(Encore.isProduction()); + * ``` + * * @param {boolean} enabled * @returns {Encore} */ @@ -424,6 +433,18 @@ class Encore { * The *type* of source map will differ between a development * or production build. * + * For example if you want to always generate sourcemaps: + * + * ``` + * Encore.enableSourceMaps(); + * ``` + * + * Or only enable them when not in production mode: + * + * ``` + * Encore.enableSourceMaps(!Encore.isProduction()); + * ``` + * * @param {boolean} enabled * @returns {Encore} */ @@ -436,6 +457,15 @@ class Encore { /** * Add a "commons" file that holds JS shared by multiple chunks/files. * + * For example: + * + * ``` + * Encore.createSharedEntry( + * 'vendor', + * './src/shared.js' + * ); + * ``` + * * @param {string} name The chunk name (e.g. vendor to create a vendor.js) * @param {string} file A file whose code & imports should be put into the shared file. * @returns {Encore}