Skip to content

Commit

Permalink
Change entrypoint configuration to be passed by environment variables.
Browse files Browse the repository at this point in the history
  • Loading branch information
pablinos committed Aug 29, 2021
1 parent b933030 commit f234ec9
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 6 deletions.
10 changes: 6 additions & 4 deletions packages/scripts/config/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,6 @@ const getLiveReloadPort = ( inputPort ) => {
const config = {
mode,
target,
entry: {
index: path.resolve( process.cwd(), 'src', 'index.js' ),
},
output: {
filename: '[name].js',
path: path.resolve( process.cwd(), 'build' ),
Expand Down Expand Up @@ -244,4 +241,9 @@ if ( ! isProduction ) {
} );
}

module.exports = config;
module.exports = ( env ) => ( {
...config,
entry: env.entries ?? {
index: path.resolve( process.cwd(), 'src', 'index.js' ),
},
} );
51 changes: 49 additions & 2 deletions packages/scripts/utils/config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
/**
* External dependencies
*/
const { basename } = require( 'path' );

/**
* Internal dependencies
*/
const { getArgsFromCLI, hasArgInCLI } = require( './cli' );
const {
getArgsFromCLI,
getFileArgsFromCLI,
hasArgInCLI,
hasFileArgInCLI,
} = require( './cli' );
const { fromConfigRoot, fromProjectRoot, hasProjectFile } = require( './file' );
const { hasPackageProp } = require( './package' );

Expand Down Expand Up @@ -94,7 +104,44 @@ const hasPostCSSConfig = () =>
*/
const getWebpackArgs = () => {
// Gets all args from CLI without those prefixed with `--webpack`.
const webpackArgs = getArgsFromCLI( [ '--webpack' ] );
let webpackArgs = getArgsFromCLI( [ '--webpack' ] );

const hasWebpackOutputOption =
hasArgInCLI( '-o' ) || hasArgInCLI( '--output' );
if ( hasFileArgInCLI() && ! hasWebpackOutputOption ) {
/**
* Converts a path to the entry format supported by webpack, e.g.:
* `./entry-one.js` -> `entry-one=./entry-one.js`
* `entry-two.js` -> `entry-two=./entry-two.js`
*
* @param {string} path The path provided.
*
* @return {string} The entry format supported by webpack.
*/
const pathToEntry = ( path ) => {
const entry = 'entries.' + basename( path, '.js' );

if ( ! path.startsWith( './' ) ) {
path = './' + path;
}

return [ '--env', [ entry, path ].join( '=' ) ];
};

// The following handles the support for multiple entry points in webpack, e.g.:
// `wp-scripts build one.js custom=./two.js` -> `webpack one=./one.js custom=./two.js`
webpackArgs = webpackArgs.reduce( ( args, cliArg ) => {
if (
getFileArgsFromCLI().includes( cliArg ) &&
! cliArg.includes( '=' )
) {
args.push( ...pathToEntry( cliArg ) );
} else {
args.push( cliArg );
}
return args;
}, [] );
}

if ( ! hasWebpackConfig() ) {
webpackArgs.push( '--config', fromConfigRoot( 'webpack.config.js' ) );
Expand Down

0 comments on commit f234ec9

Please sign in to comment.