woocommerce/plugins/woocommerce-admin/webpack.config.js

302 lines
9.9 KiB
JavaScript
Raw Normal View History

/**
* External dependencies
*/
const { get } = require( 'lodash' );
const path = require( 'path' );
const CopyWebpackPlugin = require( 'copy-webpack-plugin' );
const CustomTemplatedPathPlugin = require( '@wordpress/custom-templated-path-webpack-plugin' );
const BundleAnalyzerPlugin =
require( 'webpack-bundle-analyzer' ).BundleAnalyzerPlugin;
Use Route based code splitting to optimize bundle size (https://github.com/woocommerce/woocommerce-admin/pull/4094) * Use lazy loading to split up the size of the js downloaded * Use lazy loading to split up the size of the js downloaded * Add Moment Timezone plugin to reduce size of data file. * Lazy load header panels and use Dashicons for faster loading * Load assets from the correct publicPath * Load assets from the correct publicPath * PHP cs fixes * Fix missing quotes on string literal. * Fix PropType warning for lazy loaded component. * Separate the task list and dashboard chunks. * Lazy load dashboard sections. * Restore original icons and reduce size by importing only the icons needed * Lazy load alerts to save more Kb on initial load * Minify built JS in production mode. * Add preload tags for WC Admin assets. (https://github.com/woocommerce/woocommerce-admin/pull/4162) * Fix linting errors. * Add modified UnminifiedWebpackPlugin. * Produce minified and unminified bundles for all builds. * Remove unused variable from webpack config. * Run unminify after sourcemap generation. * Only hook after optimization if we're using a devtool. * Add minification suffix in Loader::get_url(). * Lazy load OBW on new home screen. * Move OBW style up a level to layout. * Hydrate ProfileWizard independently of withSelect and withDispatch * Fix order of composition and fallback function when using hydration. Co-authored-by: Jeff Stieler <jeff.m.stieler@gmail.com> Co-authored-by: Paul Sealock <psealock@gmail.com>
2020-04-29 18:01:27 +00:00
const MomentTimezoneDataPlugin = require( 'moment-timezone-data-webpack-plugin' );
const ForkTsCheckerWebpackPlugin = require( 'fork-ts-checker-webpack-plugin' );
const ReactRefreshWebpackPlugin = require( '@pmmmwh/react-refresh-webpack-plugin' );
const NormalModuleReplacementPlugin =
require( 'webpack' ).NormalModuleReplacementPlugin;
/**
* Internal dependencies
*/
const UnminifyWebpackPlugin = require( './unminify' );
const {
webpackConfig: styleConfig,
} = require( '@woocommerce/internal-style-build' );
const WooCommerceDependencyExtractionWebpackPlugin = require( '../../packages/js/dependency-extraction-webpack-plugin/src/index' );
const NODE_ENV = process.env.NODE_ENV || 'development';
const WC_ADMIN_PHASE = process.env.WC_ADMIN_PHASE || 'development';
const isHot = Boolean( process.env.HOT );
const isProduction = NODE_ENV === 'production';
2018-04-17 21:38:56 +00:00
const wcAdminPackages = [
'admin-layout',
'components',
'csv-export',
'currency',
'customer-effort-score',
'date',
'experimental',
'explat',
'navigation',
'notices',
'number',
wp.data Settings refactor add data store for settings using wp.data add use-select-with-refresh example replace fresh-data usage with new settings data store for settings page Add data package move to packages Fix isDirty after save Add isBusy to primary button when saving update Readme remove comment readme to use useSelect Revert "update Readme" This reverts commit 7402fd49b8f384fde5878e0bee0616f0a87bb4f6. Data Layer: Settings page to use Settings store (https://github.com/woocommerce/woocommerce-admin/pull/3430) * Data Layer: Settings store as source of truth for settings page This reverts commit 7402fd49b8f384fde5878e0bee0616f0a87bb4f6. * fixup * save on reset * non mutable constants * add set/getSettings * save using setSettings * separate HOC * cleanup * remove settingsToData * withHydration * remove withSettings HOC * renmove useSettins for now * withSettingsHydration updates * Revert "withSettingsHydration updates" This reverts commit f2adf108fbe19b574978fea5925a1a18e7ed3007. * rename withSettingsHydration * redo withSettingsHydration simplification * restore * useSettings * render using useSettings * handleInputChange working * get setIsDirty working * saving works * reset and cleanup * cleanup * use snake case on hook files * use clearIsDirty * Avoid mutation on setting update * remove @todo * persiting -> isPersisting * better reducer ternaries * add wcSettings as arg to withSettingsHydration reset package-lock Settings: split out mutable wcAdminSettings (https://github.com/woocommerce/woocommerce-admin/pull/3675) Settings: handle async settings groups (https://github.com/woocommerce/woocommerce-admin/pull/3707)
2020-03-25 03:20:17 +00:00
'data',
'tracks',
'onboarding',
Template API: Expose template block id and order to client (#40263) * Update unit tests to handle _templateBlockId and _templateBlockOrder * Refactor get_formatted_template * Initial @woocommerce/block-templates package * Add block-templates to admin webpack * Add block-templates to dependency-extraction-webpack-plugin * Add block-templates to admin assets * Add block-templates dependency * Update name block * Update syncpack * Update regular price block * Update tab block * Update section block * Add @wordpress/deprecated to package * Deprecated initBlock * Update attributes block * Update catalog visibility block * Update checkbox block * Update conditional block * Update collapsible block * Allow additional props to be passed to useWooBlockProps * Update inventory sku block * Update inventory quantity block * Update inventory email block * Update images block * Update description block * Update radio block * Update pricing block * Update password block * Update notice block * Update shipping dimensions block * Update shipping class block * Update schedule sale block * Update sale price block * Update toggle block * Update taxonomy block * Update tag block * Update summary block * Update variations block * Update variations options block * Update variation items blocks * Changelog * Changelog * Changelog * Changelog * Changelog * Add test for registerWooBlockType * Add @testing-library/react-hooks to devDependencies * Add test for useWooBlockProps * Document API * Fix linting issues in README.md * Fix tabs tests by mocking useWooBlockProps * Allow header duplication under different nesting * Remove unused import (fixes lint error) * Update lock file
2023-09-27 20:38:56 +00:00
'block-templates',
'product-editor',
];
2022-04-12 06:47:03 +00:00
// wpAdminScripts are loaded on wp-admin pages outside the context of WooCommerce Admin
// See ./client/wp-admin-scripts/README.md for more details
const wpAdminScripts = [
Add Coupon feature (https://github.com/woocommerce/woocommerce-admin/pull/4526) * Handle new object for posts and recommendations * Set breadcrumb parent for woocommerce-coupons to be woocommerce-marketing * Add main coupon wrapping component * Render coupon wrapper element below coupon table using wp-admin-scripts * Finish off implementing category param for data store resolvers * Create a helper trait for legacy coupons * Add coupon related titles and descriptions * Add note for the coupons being moved * Allow for querying by note name in the notes Data Store * Revamp coupon moved trait * Add the new note only if we don't have an unactioned note and perform a redirect to ensure menu updates * set_icon is deprecated * Move coupon menu, adding a note for customers * Translate title and descriptions * Whitespace * Account for coupon functionality being disabled * Hide legacy menu before redirect * Don’t keep adding the note if customer dismisses it from inbox * Move behind feature flag * Add note if feature enabled * Add filter to override coupon feature * Tweak option name to refer to wc_admin To help with finding etc. * use css variables * Add the new note only if we don't have an unactioned note * Switch the filter logic so `false` turns off the feature This is a bit more intuitive when utilizing the filter * Remove extraneous string and add trailing new lines * Use correct posts object in tests * Revert accidental removal of where_types * Add coupons category to RecommendedExtensions * Use 1.1 api to get categorized recommendations * Add missing text domains * Fix menu handling to point to woocommerce-marketing * Only load coupon scripts on the coupon page * Rework marketing menu logic to register pages more properly * Use correct wc-admin path for marketing page * Remove separate feature flag WC Admin has existing feature flags to load enable/disable the feature * Only set the coupon parent to marketing when the feature is enabled * Only load coupon feature if marketing feature is enabled Co-authored-by: Dan Bitzer <danielbitzer@gmail.com> Co-authored-by: Jeremy Pry <jeremy.pry@gmail.com>
2020-06-16 02:30:41 +00:00
'marketing-coupons',
'navigation-opt-out',
'onboarding-homepage-notice',
'onboarding-product-notice',
'onboarding-product-import-notice',
'onboarding-tax-notice',
'print-shipping-label-banner',
'beta-features-tracking-modal',
'payment-method-promotions',
'onboarding-load-sample-products-notice',
'product-tracking',
'add-term-tracking',
'attributes-tracking',
'category-tracking',
'tags-tracking',
'product-tour',
'wc-addons-tour',
'settings-tracking',
'order-tracking',
'product-import-tracking',
'variable-product-tour',
'product-category-metabox',
'shipping-settings-region-picker',
'command-palette',
'command-palette-analytics',
2024-04-17 10:13:24 +00:00
'woo-connect-notice',
'woo-plugin-update-connect-notice',
'woo-enable-autorenew',
'woo-renew-subscription',
Show notice for expired and expiring subscriptions in settings and in-app extensions page (#47004) * show notice on WC core about subs expired * add notice in wc core my subscription page * dismiss subscription notice * add rest api for dismiss subscription notioce * dismiss notice permanently * code refactor * fix issue in expired subs * not showing expiring subs notice if expired sub notice render not showing expiring subs notice if expired sub notice render * fix lint * added changelog * update comment * fix js lint * update response * added new endpoint for notice * update the endpoint URL * update the endpoint URL * show notice after one month * add css class for refactor * fix lint * Add missing callback after the merge * check plugin is installed on current site * add comments, and fix missing price * fix lint * remove unnecessary duplicate asset load * fix notice so that it only trigger dismiss API on notices close * localize the renew product price * track events in the wc settings page * Use the correct field product_regular_price instead of product_price * Add missing period in the notice message * add nonce to the dismiss notice API * extract dismiss notice API call to different code * extract expired and expiring component to 1 component * add track events for tsx components * fix nonce checking * fix lint * fix lint * enrich the button and hyperlink url to contains the product_id of expiring / expired subscription * fix lint * fix lint --------- Co-authored-by: Akeda Bagus <akeda.bagus@automattic.com> Co-authored-by: prahesa.setia <prahesa.kusuma.setia@automattic.com>
2024-05-31 01:34:36 +00:00
'woo-subscriptions-notice',
'woo-product-usage-notice',
];
const getEntryPoints = () => {
const entryPoints = {
app: './client/index.js',
};
wcAdminPackages.forEach( ( name ) => {
entryPoints[ name ] = `../../packages/js/${ name }`;
} );
wpAdminScripts.forEach( ( name ) => {
entryPoints[ name ] = `./client/wp-admin-scripts/${ name }`;
} );
return entryPoints;
};
// WordPress.orgs translation infrastructure ignores files named “.min.js” so we need to name our JS files without min when releasing the plugin.
const outputSuffix = WC_ADMIN_PHASE === 'core' ? '' : '.min';
2018-04-17 21:38:56 +00:00
const webpackConfig = {
mode: NODE_ENV,
entry: getEntryPoints(),
2018-04-17 21:38:56 +00:00
output: {
filename: ( data ) => {
2022-04-12 06:47:03 +00:00
// Output wpAdminScripts to wp-admin-scripts folder
// See https://github.com/woocommerce/woocommerce-admin/pull/3061
return wpAdminScripts.includes( data.chunk.name )
? `wp-admin-scripts/[name]${ outputSuffix }.js`
: `[name]/index${ outputSuffix }.js`;
},
chunkFilename: `chunks/[name]${ outputSuffix }.js?ver=[contenthash]`,
path: path.join( __dirname, '/build' ),
library: {
// Expose the exports of entry points so we can consume the libraries in window.wc.[modulename] with WooCommerceDependencyExtractionWebpackPlugin.
name: [ 'wc', '[modulename]' ],
type: 'window',
},
2022-04-12 06:47:03 +00:00
// A unique name of the webpack build to avoid multiple webpack runtimes to conflict when using globals.
uniqueName: '__wcAdmin_webpackJsonp',
2018-04-17 21:38:56 +00:00
},
module: {
parser: styleConfig.parser,
2018-04-17 21:38:56 +00:00
rules: [
{
test: /\.(t|j)sx?$/,
parser: {
2022-04-12 06:47:03 +00:00
// Disable AMD to fix an issue where underscore and lodash where clashing
// See https://github.com/woocommerce/woocommerce-admin/pull/1004 and https://github.com/Automattic/woocommerce-services/pull/1522
amd: false,
},
exclude: [
// Exclude node_modules/.pnpm
/node_modules(\/|\\)\.pnpm(\/|\\)/,
],
use: {
loader: 'babel-loader',
options: {
presets: [
'@wordpress/babel-preset-default',
[
'@babel/preset-env',
{
2022-04-12 06:47:03 +00:00
// Add polyfills such as Array.flat based on their usage in the code
// See https://github.com/woocommerce/woocommerce-admin/pull/6411/
corejs: '3',
useBuiltIns: 'usage',
},
],
[ '@babel/preset-typescript' ],
],
plugins: [
'@babel/plugin-proposal-class-properties',
! isProduction &&
isHot &&
require.resolve( 'react-refresh/babel' ),
].filter( Boolean ),
cacheDirectory: path.resolve(
__dirname,
'../../node_modules/.cache/babel-loader'
),
cacheCompression: false,
},
},
},
{ test: /\.md$/, use: 'raw-loader' },
{
test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/,
type: 'asset',
},
...styleConfig.rules,
2018-04-17 21:38:56 +00:00
],
},
resolve: {
2022-04-12 06:47:03 +00:00
fallback: {
// Reduce bundle size by omitting Node crypto library.
// See https://github.com/woocommerce/woocommerce-admin/pull/5768
crypto: 'empty',
// Ignore fs, path to skip resolve errors for @automattic/calypso-config
fs: false,
path: false,
},
extensions: [ '.json', '.js', '.jsx', '.ts', '.tsx' ],
2018-07-20 03:40:15 +00:00
alias: {
'~': path.resolve( __dirname + '/client' ),
2018-07-20 03:40:15 +00:00
},
},
plugins: [
2023-10-24 04:28:39 +00:00
// Workaround for Gutenberg private API consent string differences between WP 6.3 and 6.4+
2023-10-24 00:25:09 +00:00
// The modified version checks for the WP version and replaces the consent string with the correct one.
// This can be removed once we drop support for WP 6.3 in the "Customize Your Store" task.
2023-10-24 04:29:18 +00:00
// See this PR for details: https://github.com/woocommerce/woocommerce/pull/40884
new NormalModuleReplacementPlugin(
/@wordpress\/edit-site\/build-module\/lock-unlock\.js/,
path.resolve( __dirname, 'bin/modified-editsite-lock-unlock.js' )
),
...styleConfig.plugins,
2022-04-12 06:47:03 +00:00
// Runs TypeScript type checker on a separate process.
! process.env.STORYBOOK && new ForkTsCheckerWebpackPlugin(),
new CustomTemplatedPathPlugin( {
modulename( outputPath, data ) {
const entryName = get( data, [ 'chunk', 'name' ] );
if ( entryName ) {
2022-04-12 06:47:03 +00:00
// Convert the dash-case name to a camel case module name.
// For example, 'csv-export' -> 'csvExport'
return entryName.replace( /-([a-z])/g, ( match, letter ) =>
letter.toUpperCase()
);
}
return outputPath;
},
} ),
2022-04-12 06:47:03 +00:00
// The package build process doesn't handle extracting CSS from JS files, so we copy them separately.
new CopyWebpackPlugin( {
patterns: wcAdminPackages.map( ( packageName ) => ( {
// Copy css and style.asset.php files.
from: `../../packages/js/${ packageName }/build-style/*.{css,php}`,
to: `./${ packageName }/[name][ext]`,
2022-04-12 06:47:03 +00:00
noErrorOnMissing: true,
// Overwrites files already in compilation.assets to ensure we use the assets from the build-style.
// This is required for @woocommerce/component to use @automattic/* packages because scss styles from @automattic/* packages will be automatically generated by mini-css-extract-plugin with the same output name.
force: true,
2022-04-12 06:47:03 +00:00
} ) ),
} ),
// Get all product editor blocks so they can be loaded via JSON.
new CopyWebpackPlugin( {
patterns: [
{
from: '../../packages/js/product-editor/build/blocks',
to: './product-editor/blocks',
},
],
} ),
// React Fast Refresh.
! isProduction && isHot && new ReactRefreshWebpackPlugin(),
// We reuse this Webpack setup for Storybook, where we need to disable dependency extraction.
! process.env.STORYBOOK &&
new WooCommerceDependencyExtractionWebpackPlugin( {
requestToExternal( request ) {
if ( request === '@wordpress/components/build/ui' ) {
// The external wp.components does not include ui components, so we need to skip requesting to external here.
return null;
}
if ( request.startsWith( '@wordpress/edit-site' ) ) {
// The external wp.editSite does not include edit-site components, so we need to skip requesting to external here. We can remove this once the edit-site components are exported in the external wp.editSite.
// We use the edit-site components in the customize store.
return null;
}
},
} ),
2022-04-12 06:47:03 +00:00
// Reduces data for moment-timezone.
Use Route based code splitting to optimize bundle size (https://github.com/woocommerce/woocommerce-admin/pull/4094) * Use lazy loading to split up the size of the js downloaded * Use lazy loading to split up the size of the js downloaded * Add Moment Timezone plugin to reduce size of data file. * Lazy load header panels and use Dashicons for faster loading * Load assets from the correct publicPath * Load assets from the correct publicPath * PHP cs fixes * Fix missing quotes on string literal. * Fix PropType warning for lazy loaded component. * Separate the task list and dashboard chunks. * Lazy load dashboard sections. * Restore original icons and reduce size by importing only the icons needed * Lazy load alerts to save more Kb on initial load * Minify built JS in production mode. * Add preload tags for WC Admin assets. (https://github.com/woocommerce/woocommerce-admin/pull/4162) * Fix linting errors. * Add modified UnminifiedWebpackPlugin. * Produce minified and unminified bundles for all builds. * Remove unused variable from webpack config. * Run unminify after sourcemap generation. * Only hook after optimization if we're using a devtool. * Add minification suffix in Loader::get_url(). * Lazy load OBW on new home screen. * Move OBW style up a level to layout. * Hydrate ProfileWizard independently of withSelect and withDispatch * Fix order of composition and fallback function when using hydration. Co-authored-by: Jeff Stieler <jeff.m.stieler@gmail.com> Co-authored-by: Paul Sealock <psealock@gmail.com>
2020-04-29 18:01:27 +00:00
new MomentTimezoneDataPlugin( {
2022-04-12 06:47:03 +00:00
// This strips out timezone data before the year 2000 to make a smaller file.
startYear: 2000,
Use Route based code splitting to optimize bundle size (https://github.com/woocommerce/woocommerce-admin/pull/4094) * Use lazy loading to split up the size of the js downloaded * Use lazy loading to split up the size of the js downloaded * Add Moment Timezone plugin to reduce size of data file. * Lazy load header panels and use Dashicons for faster loading * Load assets from the correct publicPath * Load assets from the correct publicPath * PHP cs fixes * Fix missing quotes on string literal. * Fix PropType warning for lazy loaded component. * Separate the task list and dashboard chunks. * Lazy load dashboard sections. * Restore original icons and reduce size by importing only the icons needed * Lazy load alerts to save more Kb on initial load * Minify built JS in production mode. * Add preload tags for WC Admin assets. (https://github.com/woocommerce/woocommerce-admin/pull/4162) * Fix linting errors. * Add modified UnminifiedWebpackPlugin. * Produce minified and unminified bundles for all builds. * Remove unused variable from webpack config. * Run unminify after sourcemap generation. * Only hook after optimization if we're using a devtool. * Add minification suffix in Loader::get_url(). * Lazy load OBW on new home screen. * Move OBW style up a level to layout. * Hydrate ProfileWizard independently of withSelect and withDispatch * Fix order of composition and fallback function when using hydration. Co-authored-by: Jeff Stieler <jeff.m.stieler@gmail.com> Co-authored-by: Paul Sealock <psealock@gmail.com>
2020-04-29 18:01:27 +00:00
} ),
process.env.ANALYZE && new BundleAnalyzerPlugin(),
// We only want to generate unminified files in the development phase.
WC_ADMIN_PHASE === 'development' &&
// Generate unminified files to load the unminified version when `define( 'SCRIPT_DEBUG', true );` is set in wp-config.
new UnminifyWebpackPlugin( {
test: /\.js($|\?)/i,
mainEntry: 'app/index.min.js',
} ),
Use Route based code splitting to optimize bundle size (https://github.com/woocommerce/woocommerce-admin/pull/4094) * Use lazy loading to split up the size of the js downloaded * Use lazy loading to split up the size of the js downloaded * Add Moment Timezone plugin to reduce size of data file. * Lazy load header panels and use Dashicons for faster loading * Load assets from the correct publicPath * Load assets from the correct publicPath * PHP cs fixes * Fix missing quotes on string literal. * Fix PropType warning for lazy loaded component. * Separate the task list and dashboard chunks. * Lazy load dashboard sections. * Restore original icons and reduce size by importing only the icons needed * Lazy load alerts to save more Kb on initial load * Minify built JS in production mode. * Add preload tags for WC Admin assets. (https://github.com/woocommerce/woocommerce-admin/pull/4162) * Fix linting errors. * Add modified UnminifiedWebpackPlugin. * Produce minified and unminified bundles for all builds. * Remove unused variable from webpack config. * Run unminify after sourcemap generation. * Only hook after optimization if we're using a devtool. * Add minification suffix in Loader::get_url(). * Lazy load OBW on new home screen. * Move OBW style up a level to layout. * Hydrate ProfileWizard independently of withSelect and withDispatch * Fix order of composition and fallback function when using hydration. Co-authored-by: Jeff Stieler <jeff.m.stieler@gmail.com> Co-authored-by: Paul Sealock <psealock@gmail.com>
2020-04-29 18:01:27 +00:00
].filter( Boolean ),
optimization: {
minimize: NODE_ENV !== 'development',
splitChunks: {
2022-04-12 06:47:03 +00:00
// Not to generate chunk names because it caused a stressful workflow when deploying the plugin to WP.org
// See https://github.com/woocommerce/woocommerce-admin/pull/5229
name: false,
},
},
2018-04-17 21:38:56 +00:00
};
if ( ! isProduction || WC_ADMIN_PHASE === 'development' ) {
// Set default sourcemap mode if it wasn't set by WP_DEVTOOL.
webpackConfig.devtool = webpackConfig.devtool || 'source-map';
if ( isHot ) {
// Add dev server config
// Copied from https://github.com/WordPress/gutenberg/blob/05bea6dd5c6198b0287c41a401d36a06b48831eb/packages/scripts/config/webpack.config.js#L312-L326
webpackConfig.devServer = {
devMiddleware: {
writeToDisk: true,
},
allowedHosts: 'auto',
host: 'localhost',
port: 8887,
proxy: {
'/build': {
pathRewrite: {
'^/build': '',
},
},
},
};
}
}
2018-04-17 21:38:56 +00:00
module.exports = webpackConfig;