woocommerce/plugins/woocommerce-blocks/bin/webpack-configs.js

865 lines
21 KiB
JavaScript
Raw Normal View History

/**
* External dependencies
*/
const path = require( 'path' );
Fix missing translations in inspector (https://github.com/woocommerce/woocommerce-blocks/pull/6737) * Try registering the "cart taxes" inner block Registering server side. This example isn't working, but I'm pushing to share it and see what's wrong with this implementation. * Fix registering the cart taxes inner block issue * Update translation script loading * Remove unnecessary JS translation The translation should work fine by getting the title & description from the `block.json` file * Put back the initial code in the 'Cart Taxes' inner block We didn't provide the correct `block.json` file path server side, that's why the `metadata` wasn't correctly registered * Generate `block.json`files for inner blocks This is the first step on fixing the missing translations of `metadata` in `block.json` files * Set the folder name exactly the same as the inner block name We are doing this first test for the `Cart taxes` inner block. The `Block` & its containing folder need to have the same name for: - Consistency - We use the `Block` name to get the file Path * Update imports after folder renaming * Get block name directly from the JSON metadata Getting the block name from the JSON metadata is less error prone than extracting it from the file path. And no need to rename all our `inner-blocks` to get the correct `block.json` path * Revert folder naming change of `Cart taxes` inner block Since we are getting the `block` name directly from the `block.json` metadata instead of extracting it from the file path, there is no need to keep their names in sync anymore * Fix missing translations for the `Cart Subtotal` Block * Register only the client-side settings on the client When the block is registered on the server, you only need to register the client-side settings on the client using the same block’s name. See [docs](https://github.com/WordPress/gutenberg/blob/trunk/docs/reference-guides/block-api/block-metadata.md#javascript-client-side). * Add schema validation to `block.json` Development is improved by using a defined schema definition file. Supported editors can provide help like tooltips, autocomplete, and schema validation. * Use the same `editor_script` as the parent block This prevents WordPress from generating script tags to inexistant inner blocks JS files * Add C&C inner blocks in Cart.php & Checkout.php This is a refactoring to keep the block types controller file less overloaded * Fix all Cart inner blocks missing translations * Create the "AbstractInnerBlock" class The "Inner Blocks" will use their parent's script, so no need to create new scripts for each one of them And, our "Inner Blocks" should always be registered using the metadata file * Update the "Inner Blocks" PHP classes * Fix PHP lint erros & update function description * Fix missing translations bug for all Checkout Inner Blocks * Update src/BlockTypes/Checkout.php Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com> * skip lazy loaded scripts Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2022-08-01 14:57:33 +00:00
const fs = require( 'fs' );
2023-04-28 10:29:45 +00:00
const { paramCase } = require( 'change-case' );
const RemoveFilesPlugin = require( './remove-files-webpack-plugin' );
const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' );
const ProgressBarPlugin = require( 'progress-bar-webpack-plugin' );
const DependencyExtractionWebpackPlugin = require( '@wordpress/dependency-extraction-webpack-plugin' );
const WebpackRTLPlugin = require( 'webpack-rtl-plugin' );
const TerserPlugin = require( 'terser-webpack-plugin' );
const CreateFileWebpack = require( 'create-file-webpack' );
const CircularDependencyPlugin = require( 'circular-dependency-plugin' );
const { BundleAnalyzerPlugin } = require( 'webpack-bundle-analyzer' );
const CopyWebpackPlugin = require( 'copy-webpack-plugin' );
/**
* Internal dependencies
*/
const { getEntryConfig } = require( './webpack-entries' );
const {
ASSET_CHECK,
NODE_ENV,
CHECK_CIRCULAR_DEPS,
requestToExternal,
requestToHandle,
findModuleMatch,
getProgressBarPluginConfig,
} = require( './webpack-helpers' );
const isProduction = NODE_ENV === 'production';
/**
* Shared config for all script builds.
*/
let initialBundleAnalyzerPort = 8888;
const getSharedPlugins = ( { bundleAnalyzerReportTitle } ) =>
[
CHECK_CIRCULAR_DEPS === 'true'
? new CircularDependencyPlugin( {
exclude: /node_modules/,
cwd: process.cwd(),
failOnError: 'warn',
} )
: false,
// The WP_BUNDLE_ANALYZER global variable enables a utility that represents bundle
// content as a convenient interactive zoomable treemap.
process.env.WP_BUNDLE_ANALYZER &&
new BundleAnalyzerPlugin( {
analyzerPort: initialBundleAnalyzerPort++,
reportTitle: bundleAnalyzerReportTitle,
} ),
new DependencyExtractionWebpackPlugin( {
injectPolyfill: true,
combineAssets: ASSET_CHECK,
outputFormat: ASSET_CHECK ? 'json' : 'php',
requestToExternal,
requestToHandle,
} ),
].filter( Boolean );
/**
* Build config for core packages.
*
* @param {Object} options Build options.
*/
const getCoreConfig = ( options = {} ) => {
const { alias, resolvePlugins = [] } = options;
const resolve = alias
? {
alias,
plugins: resolvePlugins,
}
: {
plugins: resolvePlugins,
};
return {
entry: getEntryConfig( 'core', options.exclude || [] ),
output: {
filename: ( chunkData ) => {
2023-04-28 10:29:45 +00:00
return `${ paramCase( chunkData.chunk.name ) }.js`;
},
path: path.resolve( __dirname, '../build/' ),
library: [ 'wc', '[name]' ],
libraryTarget: 'this',
// This fixes an issue with multiple webpack projects using chunking
// overwriting each other's chunk loader function.
// See https://webpack.js.org/configuration/output/#outputjsonpfunction
jsonpFunction: 'webpackWcBlocksJsonp',
},
module: {
rules: [
{
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
test: /\.(t|j)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader?cacheDirectory',
options: {
presets: [ '@wordpress/babel-preset-default' ],
},
},
},
{
test: /\.s[c|a]ss$/,
use: {
loader: 'ignore-loader',
},
},
],
},
plugins: [
...getSharedPlugins( { bundleAnalyzerReportTitle: 'Core' } ),
new ProgressBarPlugin( getProgressBarPluginConfig( 'Core' ) ),
new CreateFileWebpack( {
path: './',
// file name
fileName: 'blocks.ini',
// content of the file
content: `
woocommerce_blocks_phase = ${ process.env.WOOCOMMERCE_BLOCKS_PHASE || 3 }
woocommerce_blocks_env = ${ NODE_ENV }
`.trim(),
} ),
],
optimization: {
// Only concatenate modules in production, when not analyzing bundles.
concatenateModules:
isProduction && ! process.env.WP_BUNDLE_ANALYZER,
splitChunks: {
automaticNameDelimiter: '--',
},
minimizer: [
new TerserPlugin( {
cache: true,
parallel: true,
terserOptions: {
output: {
comments: /translators:/i,
},
compress: {
passes: 2,
},
mangle: {
reserved: [ '__', '_n', '_nx', '_x' ],
},
},
extractComments: false,
} ),
],
},
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
resolve: {
...resolve,
extensions: [ '.js', '.ts', '.tsx' ],
},
};
};
/**
* Build config for Blocks in the editor context.
*
* @param {Object} options Build options.
*/
const getMainConfig = ( options = {} ) => {
let { fileSuffix } = options;
const { alias, resolvePlugins = [] } = options;
fileSuffix = fileSuffix ? `-${ fileSuffix }` : '';
const resolve = alias
? {
alias,
plugins: resolvePlugins,
}
: {
plugins: resolvePlugins,
};
return {
entry: getEntryConfig( 'main', options.exclude || [] ),
output: {
devtoolNamespace: 'wc',
path: path.resolve( __dirname, '../build/' ),
// This is a cache busting mechanism which ensures that the script is loaded via the browser with a ?ver=hash
// string. The hash is based on the built file contents.
// @see https://github.com/webpack/webpack/issues/2329
// Using the ?ver string is needed here so the filename does not change between builds. The WordPress
// i18n system relies on the hash of the filename, so changing that frequently would result in broken
// translations which we must avoid.
// @see https://github.com/Automattic/jetpack/pull/20926
chunkFilename: `[name]${ fileSuffix }.js?ver=[contenthash]`,
filename: `[name]${ fileSuffix }.js`,
library: [ 'wc', 'blocks', '[name]' ],
libraryTarget: 'this',
// This fixes an issue with multiple webpack projects using chunking
// overwriting each other's chunk loader function.
// See https://webpack.js.org/configuration/output/#outputjsonpfunction
// This can be removed when moving to webpack 5:
// https://webpack.js.org/blog/2020-10-10-webpack-5-release/#automatic-unique-naming
jsonpFunction: 'webpackWcBlocksJsonp',
},
module: {
rules: [
{
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader?cacheDirectory',
options: {
presets: [ '@wordpress/babel-preset-default' ],
plugins: [
isProduction
? require.resolve(
'babel-plugin-transform-react-remove-prop-types'
)
: false,
].filter( Boolean ),
},
},
},
{
test: /\.s[c|a]ss$/,
use: {
loader: 'ignore-loader',
},
},
],
},
optimization: {
concatenateModules:
isProduction && ! process.env.WP_BUNDLE_ANALYZER,
splitChunks: {
minSize: 0,
automaticNameDelimiter: '--',
cacheGroups: {
commons: {
test: /[\/\\]node_modules[\/\\]/,
name: 'wc-blocks-vendors',
chunks: 'all',
enforce: true,
},
},
},
minimizer: [
new TerserPlugin( {
cache: true,
parallel: true,
terserOptions: {
output: {
comments: /translators:/i,
},
compress: {
passes: 2,
},
mangle: {
reserved: [ '__', '_n', '_nx', '_x' ],
},
},
extractComments: false,
} ),
],
},
plugins: [
...getSharedPlugins( { bundleAnalyzerReportTitle: 'Main' } ),
new ProgressBarPlugin( getProgressBarPluginConfig( 'Main' ) ),
new CopyWebpackPlugin( {
patterns: [
{
Product Query Block POC (Phase 1) (https://github.com/woocommerce/woocommerce-blocks/pull/6812) * Move `EditorBlock` to general `type-defs` `EditorBlock` was scoped under the `featured-items` directory at the time of its creation. It is, however, a useful type that should be shared repo-wide. For this reason, I am moving it into the `blocks` type-defs and updating all the references. * Define types for the Product Query block Also defines a more generic `WooCommerceBlockVariation` type which should be also useful in the future to implement a similar pattern. * Add Product Query utils Add two utility functions: 1. `isWooQueryBlockVariation`: is used to check whether a given block is a variation of the core Query Loop block, and also one of the allowed variations within our repo. See: `QueryVariation` enum type. 2. `setCustomQueryAttribute`: is a shorthand to set an attribute within the variation query attribute. * Refactor and cleanup the JS demo code Specifically: 1. Creates a `constant.ts` file to store all shared constants. Currently, the default variation attributes. 2. Move the variations to their own directory. One file per variation. 3. Move the inspector controls into own file and create a conditional logic to allow showing only certain settings. * Update webpack config * Add ProductQuery class * Fix `QueryVariation` enum We had changed the Products on Sale variation slug to something else, but we had forgotten to update the proper enum. * Remove unused params from `update_query` The filter we added to Gutenberg will pass the block and the page, as we might need them in the future and we want to minimize the amount of changes we'll have to do upstream. However, we currently do not use those, so I removed them from our own inner function. Co-authored-by: Lucio Giannotta <lucio.giannotta@a8c.com>
2022-08-18 08:02:21 +00:00
from: './assets/js/**/block.json',
to( { absoluteFilename } ) {
Fix missing translations in inspector (https://github.com/woocommerce/woocommerce-blocks/pull/6737) * Try registering the "cart taxes" inner block Registering server side. This example isn't working, but I'm pushing to share it and see what's wrong with this implementation. * Fix registering the cart taxes inner block issue * Update translation script loading * Remove unnecessary JS translation The translation should work fine by getting the title & description from the `block.json` file * Put back the initial code in the 'Cart Taxes' inner block We didn't provide the correct `block.json` file path server side, that's why the `metadata` wasn't correctly registered * Generate `block.json`files for inner blocks This is the first step on fixing the missing translations of `metadata` in `block.json` files * Set the folder name exactly the same as the inner block name We are doing this first test for the `Cart taxes` inner block. The `Block` & its containing folder need to have the same name for: - Consistency - We use the `Block` name to get the file Path * Update imports after folder renaming * Get block name directly from the JSON metadata Getting the block name from the JSON metadata is less error prone than extracting it from the file path. And no need to rename all our `inner-blocks` to get the correct `block.json` path * Revert folder naming change of `Cart taxes` inner block Since we are getting the `block` name directly from the `block.json` metadata instead of extracting it from the file path, there is no need to keep their names in sync anymore * Fix missing translations for the `Cart Subtotal` Block * Register only the client-side settings on the client When the block is registered on the server, you only need to register the client-side settings on the client using the same block’s name. See [docs](https://github.com/WordPress/gutenberg/blob/trunk/docs/reference-guides/block-api/block-metadata.md#javascript-client-side). * Add schema validation to `block.json` Development is improved by using a defined schema definition file. Supported editors can provide help like tooltips, autocomplete, and schema validation. * Use the same `editor_script` as the parent block This prevents WordPress from generating script tags to inexistant inner blocks JS files * Add C&C inner blocks in Cart.php & Checkout.php This is a refactoring to keep the block types controller file less overloaded * Fix all Cart inner blocks missing translations * Create the "AbstractInnerBlock" class The "Inner Blocks" will use their parent's script, so no need to create new scripts for each one of them And, our "Inner Blocks" should always be registered using the metadata file * Update the "Inner Blocks" PHP classes * Fix PHP lint erros & update function description * Fix missing translations bug for all Checkout Inner Blocks * Update src/BlockTypes/Checkout.php Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com> * skip lazy loaded scripts Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2022-08-01 14:57:33 +00:00
/**
* Getting the block name from the JSON metadata is less error prone
* than extracting it from the file path.
*/
const JSONFile = fs.readFileSync(
path.resolve( __dirname, absoluteFilename )
);
const metadata = JSON.parse( JSONFile.toString() );
const blockName = metadata.name
.split( '/' )
Fix missing translations in inspector (https://github.com/woocommerce/woocommerce-blocks/pull/6737) * Try registering the "cart taxes" inner block Registering server side. This example isn't working, but I'm pushing to share it and see what's wrong with this implementation. * Fix registering the cart taxes inner block issue * Update translation script loading * Remove unnecessary JS translation The translation should work fine by getting the title & description from the `block.json` file * Put back the initial code in the 'Cart Taxes' inner block We didn't provide the correct `block.json` file path server side, that's why the `metadata` wasn't correctly registered * Generate `block.json`files for inner blocks This is the first step on fixing the missing translations of `metadata` in `block.json` files * Set the folder name exactly the same as the inner block name We are doing this first test for the `Cart taxes` inner block. The `Block` & its containing folder need to have the same name for: - Consistency - We use the `Block` name to get the file Path * Update imports after folder renaming * Get block name directly from the JSON metadata Getting the block name from the JSON metadata is less error prone than extracting it from the file path. And no need to rename all our `inner-blocks` to get the correct `block.json` path * Revert folder naming change of `Cart taxes` inner block Since we are getting the `block` name directly from the `block.json` metadata instead of extracting it from the file path, there is no need to keep their names in sync anymore * Fix missing translations for the `Cart Subtotal` Block * Register only the client-side settings on the client When the block is registered on the server, you only need to register the client-side settings on the client using the same block’s name. See [docs](https://github.com/WordPress/gutenberg/blob/trunk/docs/reference-guides/block-api/block-metadata.md#javascript-client-side). * Add schema validation to `block.json` Development is improved by using a defined schema definition file. Supported editors can provide help like tooltips, autocomplete, and schema validation. * Use the same `editor_script` as the parent block This prevents WordPress from generating script tags to inexistant inner blocks JS files * Add C&C inner blocks in Cart.php & Checkout.php This is a refactoring to keep the block types controller file less overloaded * Fix all Cart inner blocks missing translations * Create the "AbstractInnerBlock" class The "Inner Blocks" will use their parent's script, so no need to create new scripts for each one of them And, our "Inner Blocks" should always be registered using the metadata file * Update the "Inner Blocks" PHP classes * Fix PHP lint erros & update function description * Fix missing translations bug for all Checkout Inner Blocks * Update src/BlockTypes/Checkout.php Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com> * skip lazy loaded scripts Co-authored-by: Seghir Nadir <nadir.seghir@gmail.com>
2022-08-01 14:57:33 +00:00
.at( 1 );
if ( metadata.parent )
return `./inner-blocks/${ blockName }/block.json`;
return `./${ blockName }/block.json`;
},
},
],
} ),
],
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
resolve: {
...resolve,
extensions: [ '.js', '.jsx', '.ts', '.tsx' ],
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
},
};
};
/**
* Build config for Blocks in the frontend context.
*
* @param {Object} options Build options.
*/
const getFrontConfig = ( options = {} ) => {
let { fileSuffix } = options;
const { alias, resolvePlugins = [] } = options;
fileSuffix = fileSuffix ? `-${ fileSuffix }` : '';
const resolve = alias
? {
alias,
plugins: resolvePlugins,
}
: {
plugins: resolvePlugins,
};
return {
entry: getEntryConfig( 'frontend', options.exclude || [] ),
output: {
devtoolNamespace: 'wc',
path: path.resolve( __dirname, '../build/' ),
// This is a cache busting mechanism which ensures that the script is loaded via the browser with a ?ver=hash
// string. The hash is based on the built file contents.
// @see https://github.com/webpack/webpack/issues/2329
// Using the ?ver string is needed here so the filename does not change between builds. The WordPress
// i18n system relies on the hash of the filename, so changing that frequently would result in broken
// translations which we must avoid.
// @see https://github.com/Automattic/jetpack/pull/20926
chunkFilename: `[name]-frontend${ fileSuffix }.js?ver=[contenthash]`,
filename: `[name]-frontend${ fileSuffix }.js`,
// This fixes an issue with multiple webpack projects using chunking
// overwriting each other's chunk loader function.
// See https://webpack.js.org/configuration/output/#outputjsonpfunction
// This can be removed when moving to webpack 5:
// https://webpack.js.org/blog/2020-10-10-webpack-5-release/#automatic-unique-naming
jsonpFunction: 'webpackWcBlocksJsonp',
},
module: {
rules: [
{
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader?cacheDirectory',
options: {
presets: [
[
'@wordpress/babel-preset-default',
{
modules: false,
targets: {
browsers: [
'extends @wordpress/browserslist-config',
],
},
},
],
],
plugins: [
isProduction
? require.resolve(
'babel-plugin-transform-react-remove-prop-types'
)
: false,
].filter( Boolean ),
},
},
},
{
test: /\.s[c|a]ss$/,
use: {
loader: 'ignore-loader',
},
},
],
},
optimization: {
concatenateModules:
isProduction && ! process.env.WP_BUNDLE_ANALYZER,
splitChunks: {
automaticNameDelimiter: '--',
},
minimizer: [
new TerserPlugin( {
cache: true,
parallel: true,
terserOptions: {
output: {
comments: /translators:/i,
},
compress: {
passes: 2,
},
mangle: {
reserved: [ '__', '_n', '_nx', '_x' ],
},
},
extractComments: false,
} ),
],
},
plugins: [
...getSharedPlugins( { bundleAnalyzerReportTitle: 'Frontend' } ),
new ProgressBarPlugin( getProgressBarPluginConfig( 'Frontend' ) ),
],
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
resolve: {
...resolve,
extensions: [ '.js', '.ts', '.tsx' ],
},
};
};
/**
* Build config for built-in payment gateway integrations.
*
* @param {Object} options Build options.
*/
const getPaymentsConfig = ( options = {} ) => {
const { alias, resolvePlugins = [] } = options;
const resolve = alias
? {
alias,
plugins: resolvePlugins,
}
: {
plugins: resolvePlugins,
};
return {
entry: getEntryConfig( 'payments', options.exclude || [] ),
output: {
devtoolNamespace: 'wc',
path: path.resolve( __dirname, '../build/' ),
filename: `[name].js`,
// This fixes an issue with multiple webpack projects using chunking
// overwriting each other's chunk loader function.
// See https://webpack.js.org/configuration/output/#outputjsonpfunction
jsonpFunction: 'webpackWcBlocksPaymentMethodExtensionJsonp',
},
module: {
rules: [
{
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader?cacheDirectory',
options: {
presets: [
[
'@wordpress/babel-preset-default',
{
modules: false,
targets: {
browsers: [
'extends @wordpress/browserslist-config',
],
},
},
],
],
plugins: [
isProduction
? require.resolve(
'babel-plugin-transform-react-remove-prop-types'
)
: false,
].filter( Boolean ),
},
},
},
{
test: /\.s[c|a]ss$/,
use: {
loader: 'ignore-loader',
},
},
],
},
optimization: {
concatenateModules:
isProduction && ! process.env.WP_BUNDLE_ANALYZER,
splitChunks: {
automaticNameDelimiter: '--',
},
minimizer: [
new TerserPlugin( {
cache: true,
parallel: true,
terserOptions: {
output: {
comments: /translators:/i,
},
compress: {
passes: 2,
},
mangle: {
reserved: [ '__', '_n', '_nx', '_x' ],
},
},
extractComments: false,
} ),
],
},
plugins: [
...getSharedPlugins( {
bundleAnalyzerReportTitle: 'Payment Method Extensions',
} ),
new ProgressBarPlugin(
getProgressBarPluginConfig( 'Payment Method Extensions' )
),
],
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
resolve: {
...resolve,
extensions: [ '.js', '.ts', '.tsx' ],
},
};
};
/**
* Build config for extension integrations.
*
* @param {Object} options Build options.
*/
const getExtensionsConfig = ( options = {} ) => {
const { alias, resolvePlugins = [] } = options;
const resolve = alias
? {
alias,
plugins: resolvePlugins,
}
: {
plugins: resolvePlugins,
};
return {
entry: getEntryConfig( 'extensions', options.exclude || [] ),
output: {
devtoolNamespace: 'wc',
path: path.resolve( __dirname, '../build/' ),
filename: `[name].js`,
jsonpFunction: 'webpackWcBlocksExtensionsMethodExtensionJsonp',
},
module: {
rules: [
{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader?cacheDirectory',
options: {
presets: [
[
'@wordpress/babel-preset-default',
{
modules: false,
targets: {
browsers: [
'extends @wordpress/browserslist-config',
],
},
},
],
],
plugins: [
isProduction
? require.resolve(
'babel-plugin-transform-react-remove-prop-types'
)
: false,
].filter( Boolean ),
},
},
},
{
test: /\.s[c|a]ss$/,
use: {
loader: 'ignore-loader',
},
},
],
},
optimization: {
concatenateModules:
isProduction && ! process.env.WP_BUNDLE_ANALYZER,
splitChunks: {
automaticNameDelimiter: '--',
},
minimizer: [
new TerserPlugin( {
cache: true,
parallel: true,
terserOptions: {
output: {
comments: /translators:/i,
},
compress: {
passes: 2,
},
mangle: {
reserved: [ '__', '_n', '_nx', '_x' ],
},
},
extractComments: false,
} ),
],
},
plugins: [
...getSharedPlugins( {
bundleAnalyzerReportTitle: 'Experimental Extensions',
} ),
new ProgressBarPlugin(
getProgressBarPluginConfig( 'Experimental Extensions' )
),
],
resolve: {
...resolve,
extensions: [ '.js', '.ts', '.tsx' ],
},
};
};
/**
* Build config for CSS Styles.
*
* @param {Object} options Build options.
*/
const getStylingConfig = ( options = {} ) => {
let { fileSuffix } = options;
const { alias, resolvePlugins = [] } = options;
fileSuffix = fileSuffix ? `-${ fileSuffix }` : '';
const resolve = alias
? {
alias,
plugins: resolvePlugins,
}
: {
plugins: resolvePlugins,
};
return {
entry: getEntryConfig( 'styling', options.exclude || [] ),
output: {
devtoolNamespace: 'wc',
path: path.resolve( __dirname, '../build/' ),
filename: `[name]-style${ fileSuffix }.js`,
library: [ 'wc', 'blocks', '[name]' ],
libraryTarget: 'this',
// This fixes an issue with multiple webpack projects using chunking
// overwriting each other's chunk loader function.
// See https://webpack.js.org/configuration/output/#outputjsonpfunction
jsonpFunction: 'webpackWcBlocksJsonp',
},
optimization: {
splitChunks: {
minSize: 0,
automaticNameDelimiter: '--',
cacheGroups: {
editorStyle: {
// Capture all `editor` stylesheets and editor-components stylesheets.
test: ( module = {} ) =>
module.constructor.name === 'CssModule' &&
( findModuleMatch( module, /editor\.scss$/ ) ||
findModuleMatch(
module,
/[\\/]assets[\\/]js[\\/]editor-components[\\/]/
) ),
name: 'wc-blocks-editor-style',
chunks: 'all',
priority: 10,
},
vendorsStyle: {
test: /[\/\\]node_modules[\/\\].*?style\.s?css$/,
name: 'wc-blocks-vendors-style',
chunks: 'all',
priority: 7,
},
blocksStyle: {
// Capture all stylesheets with name `style` or name that starts with underscore (abstracts).
test: /(style|_.*)\.scss$/,
name: 'wc-blocks-style',
chunks: 'all',
priority: 5,
},
},
},
},
module: {
rules: [
{
test: /[\/\\]node_modules[\/\\].*?style\.s?css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader',
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths: [ 'node_modules' ],
},
additionalData: ( content ) => {
const styleImports = [
'colors',
'breakpoints',
'variables',
'mixins',
'animations',
'z-index',
]
.map(
( imported ) =>
`@import "~@wordpress/base-styles/${ imported }";`
)
.join( ' ' );
return styleImports + content;
},
},
},
],
},
{
test: /\.s?css$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader',
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths: [ 'assets/css/abstracts' ],
},
additionalData: ( content, loaderContext ) => {
const { resourcePath, rootContext } =
loaderContext;
const relativePath = path.relative(
rootContext,
resourcePath
);
if (
relativePath.startsWith(
'assets/css/abstracts/'
) ||
relativePath.startsWith(
'assets\\css\\abstracts\\'
)
) {
return content;
}
return (
'@use "sass:math";' +
'@use "sass:string";' +
'@use "sass:color";' +
'@use "sass:map";' +
'@import "_colors"; ' +
'@import "_variables"; ' +
'@import "_breakpoints"; ' +
'@import "_mixins"; ' +
content
);
},
},
},
],
},
],
},
plugins: [
new ProgressBarPlugin( getProgressBarPluginConfig( 'Styles' ) ),
new WebpackRTLPlugin( {
filename: `[name]${ fileSuffix }-rtl.css`,
minify: {
safe: true,
},
} ),
new MiniCssExtractPlugin( {
filename: `[name]${ fileSuffix }.css`,
} ),
// Remove JS files generated by MiniCssExtractPlugin.
new RemoveFilesPlugin( `./build/*style${ fileSuffix }.js` ),
],
Add TypeScript support and convert cart data store to TypeScript (https://github.com/woocommerce/woocommerce-blocks/pull/3768) * add typescript support * Add type declarations for Cart and CartResponse interfaces * make sure we’re resolving .ts files as well as .js files on imports * add more types * type the cart data store * Apply suggestions from code review (implement .tsx in configs) Co-authored-by: Jon Surrell <jon.surrell@automattic.com> * remove global fetchMock declaration and directly import where used. * rename type * remove named action types and just infer by returning action creator values as const * use interface instead of type * rename * renames * create CartAction type as union of action creator returned types and implement in reducer * remove unused imports * refresh package-lock after rebase * Add base TS config that projects will inherit from * Add tsconfig for assets/js/data project * Ignore TS error on cart store registration We will address this in cooldown when we have time to investigate further * Add tsc to build step to catch TypeScript errors * add a separate command for tsc and tweak build command to use * restore checkJs and allowJs values in config and remove ts check from build command * Add ts:check-all command * Add TypeScript checking workflows * Change triggers for TypeScript workflow * Use npm ci instead of npm install * Remove ts:check-all from TypeScript workflow * Remove TS Check GitHub workflow * Remove type-defs dir from TS include, and remove ts:check-all script We no longer need the ts:check-all script because ts:check will do this for us, the old ts:check did nothing and did not work. * fix coupon loading issues * include .ts files only from type-defs folder Co-authored-by: Jon Surrell <jon.surrell@automattic.com> Co-authored-by: Thomas Roberts <thomas.roberts@automattic.com>
2021-02-24 01:36:24 +00:00
resolve: {
...resolve,
extensions: [ '.js', '.ts', '.tsx' ],
},
};
};
const getInteractivityAPIConfig = ( options = {} ) => {
const { alias, resolvePlugins = [] } = options;
return {
entry: {
runtime: './assets/js/interactivity',
},
output: {
filename: 'woo-directives-[name].js',
path: path.resolve( __dirname, '../build/' ),
},
resolve: {
alias,
plugins: resolvePlugins,
extensions: [ '.js', '.ts', '.tsx' ],
},
plugins: [
...getSharedPlugins( {
bundleAnalyzerReportTitle: 'WP directives',
} ),
new ProgressBarPlugin(
getProgressBarPluginConfig( 'WP directives' )
),
],
optimization: {
runtimeChunk: {
name: 'vendors',
},
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
minSize: 0,
chunks: 'all',
},
},
},
},
module: {
rules: [
{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: [
{
loader: require.resolve( 'babel-loader' ),
options: {
cacheDirectory:
process.env.BABEL_CACHE_DIRECTORY || true,
babelrc: false,
configFile: false,
presets: [
[
'@babel/preset-react',
{
runtime: 'automatic',
importSource: 'preact',
},
],
],
plugins: [
'@babel/plugin-proposal-optional-chaining',
],
},
},
],
},
],
},
};
};
module.exports = {
getCoreConfig,
getFrontConfig,
getMainConfig,
getPaymentsConfig,
getExtensionsConfig,
getStylingConfig,
getInteractivityAPIConfig,
};