1
1
import rollupGlobals from 'rollup-plugin-external-globals' ;
2
2
import type { PluginOption } from 'vite' ;
3
- import viteExternal from 'vite-plugin-external' ;
4
- import { WP_EXTERNAL_PACKAGES } from '../utils/index.js' ;
3
+ import viteExternalPlugin from 'vite-plugin-external' ;
4
+ import {
5
+ BUNDLED_WP_PACKAGES ,
6
+ NON_WP_PACKAGES ,
7
+ WP_EXTERNAL_PACKAGES ,
8
+ dashToCamelCase ,
9
+ } from '../utils/index.js' ;
10
+
11
+ const viteExternal =
12
+ // viteExternalPlugin is not typed well
13
+ viteExternalPlugin as unknown as ( typeof viteExternalPlugin ) [ 'default' ] ;
14
+
15
+ function shouldExternalizePakage ( name : string ) {
16
+ if ( BUNDLED_WP_PACKAGES . includes ( name ) ) {
17
+ return false ;
18
+ }
19
+
20
+ const isWpPackage = name . startsWith ( '@wordpress/' ) ;
21
+
22
+ const isNonWpPackage = name in NON_WP_PACKAGES ;
23
+
24
+ return isWpPackage || isNonWpPackage ;
25
+ }
5
26
6
27
/**
7
28
* Updates the vite config to externalize all WordPress packages.
@@ -10,28 +31,59 @@ export const externalizeWpPackages = (): PluginOption => {
10
31
return [
11
32
{
12
33
name : 'vwpr:externalize-wp-packages' ,
13
- config ( ) {
34
+ config ( config , { command } ) {
35
+ // We need to run this only for the build command
36
+ if ( command !== 'build' ) {
37
+ return { } ;
38
+ }
14
39
return {
15
40
build : {
16
41
rollupOptions : {
17
- external : Object . keys ( WP_EXTERNAL_PACKAGES ) ,
42
+ external ( source ) {
43
+ return shouldExternalizePakage ( source ) ;
44
+ } ,
18
45
plugins : [
19
46
/**
20
47
* Add the plugin to rollup to ensure react imports don't end up in the bundle
21
48
* framer-motion causes the issue by using namespace imports
22
49
*
23
50
* @see https://github.com/vitejs/vite-plugin-react/issues/3
24
51
*/
25
- rollupGlobals ( WP_EXTERNAL_PACKAGES ) ,
52
+ rollupGlobals ( ( name ) => {
53
+ if ( ! shouldExternalizePakage ( name ) ) {
54
+ return '' ;
55
+ }
56
+
57
+ if ( name in NON_WP_PACKAGES ) {
58
+ return NON_WP_PACKAGES [ name ] ;
59
+ }
60
+
61
+ if ( name . startsWith ( '@wordpress/' ) ) {
62
+ const variable = dashToCamelCase (
63
+ name . replace ( '@wordpress/' , '' ) ,
64
+ ) ;
65
+ return `wp.${ variable } ` ;
66
+ }
67
+
68
+ return '' ;
69
+ } ) ,
26
70
] ,
27
71
} ,
28
72
} ,
29
73
} ;
30
74
} ,
31
75
} ,
32
- // @ts -ignore - viteExternal is not typed well
76
+ /**
77
+ * We need this plugin only during development
78
+ * To ensure that module aliases are created for external packages
79
+ *
80
+ * Change the externals list to dynamic if the below issue is resolved
81
+ * @see https://github.com/fengxinming/vite-plugins/issues/44
82
+ */
33
83
viteExternal ( {
34
- externals : WP_EXTERNAL_PACKAGES ,
84
+ development : {
85
+ externals : WP_EXTERNAL_PACKAGES ,
86
+ } ,
35
87
} ) ,
36
88
] ;
37
89
} ;
0 commit comments