Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(template-compiler): dynamic components #3337

Merged
merged 14 commits into from
Feb 20, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/@lwc/compiler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export {
TransformOptions,
StylesheetConfig,
CustomPropertiesResolution,
DynamicComponentConfig,
DynamicImportConfig,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change will need a co-ordinated change in lwc-platform

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also needs a coordinated release as experimentalDynamicDirective should now be available as a compiler option.

OutputConfig,
} from './options';

Expand Down
22 changes: 15 additions & 7 deletions packages/@lwc/compiler/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const DEFAULT_OPTIONS = {
disableSyntheticShadowSupport: false,
};

const DEFAULT_DYNAMIC_CMP_CONFIG: Required<DynamicComponentConfig> = {
const DEFAULT_DYNAMIC_IMPORT_CONFIG: Required<DynamicImportConfig> = {
loader: '',
strictSpecifier: true,
};
Expand Down Expand Up @@ -56,7 +56,7 @@ export interface OutputConfig {
minify?: boolean;
}

export interface DynamicComponentConfig {
export interface DynamicImportConfig {
loader?: string;
strictSpecifier?: boolean;
}
Expand All @@ -65,7 +65,10 @@ export interface TransformOptions {
name?: string;
namespace?: string;
stylesheetConfig?: StylesheetConfig;
experimentalDynamicComponent?: DynamicComponentConfig;
dynamicImportConfig?: DynamicImportConfig;
jmsjtu marked this conversation as resolved.
Show resolved Hide resolved
// TODO [#3331]: remove usage of lwc:dynamic in 246
experimentalDynamicDirective?: boolean;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, these old types are best left alone for deprecation later.

The cascading effect of changing the existing types will become a overhead to manage. Here are some the repos that depend on this type:

  1. lwc-platform
  2. lwc-test

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I debated about this initially but I think you're right. Changing these compiler options will lead to unnecessary overhead in managing the release of this feature to downstream dependencies.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've changed dynamicImportConfig back to experimentalDynamicComponents to prevent breaking downstream consumers and to ease the enablement of this feature.

We're planning to remove the lwc:dynamic directive entirely in 246 and I plan to deprecate experimentalDynamicComponent in favor of dynamicImportConfig as part of it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove this from the PR description!
Screenshot 2023-02-10 at 12 27 57 PM

enableDynamicComponents?: boolean;
jmsjtu marked this conversation as resolved.
Show resolved Hide resolved
outputConfig?: OutputConfig;
isExplicitImport?: boolean;
preserveHtmlComments?: boolean;
Expand All @@ -85,6 +88,8 @@ type RequiredTransformOptions = Omit<
| 'customRendererConfig'
| 'enableLwcSpread'
| 'enableScopedSlots'
| 'enableDynamicComponents'
| 'experimentalDynamicDirective'
jmsjtu marked this conversation as resolved.
Show resolved Hide resolved
>;
export interface NormalizedTransformOptions extends RecursiveRequired<RequiredTransformOptions> {
name?: string;
Expand All @@ -93,6 +98,9 @@ export interface NormalizedTransformOptions extends RecursiveRequired<RequiredTr
customRendererConfig?: CustomRendererConfig;
enableLwcSpread?: boolean;
enableScopedSlots?: boolean;
enableDynamicComponents?: boolean;
// TODO [#3331]: remove usage of lwc:dynamic in 246
experimentalDynamicDirective?: boolean;
}

export function validateTransformOptions(options: TransformOptions): NormalizedTransformOptions {
Expand Down Expand Up @@ -165,16 +173,16 @@ function normalizeOptions(options: TransformOptions): NormalizedTransformOptions
},
};

const experimentalDynamicComponent: Required<DynamicComponentConfig> = {
...DEFAULT_DYNAMIC_CMP_CONFIG,
...options.experimentalDynamicComponent,
const dynamicImportConfig: Required<DynamicImportConfig> = {
...DEFAULT_DYNAMIC_IMPORT_CONFIG,
...options.dynamicImportConfig,
};

return {
...DEFAULT_OPTIONS,
...options,
stylesheetConfig,
outputConfig,
experimentalDynamicComponent,
dynamicImportConfig,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,69 @@ describe('transformSync', () => {
expect(warnings).toHaveLength(0);
expect(code).not.toMatch('renderer: renderer');
});

jmsjtu marked this conversation as resolved.
Show resolved Hide resolved
it('should allow dynamic components when enableDynamicComponents is set to true', () => {
const template = `
<template>
<lwc:component lwc:is={ctor}></lwc:component>
</template>
`;
const { code, warnings } = transformSync(template, 'foo.html', {
enableDynamicComponents: true,
...TRANSFORMATION_OPTIONS,
});

expect(warnings).toHaveLength(0);
expect(code).toContain('api_dynamic_component');
});

it('should not allow dynamic components when enableDynamicComponents is set to false', () => {
const template = `
<template>
<lwc:component lwc:is={ctor}></lwc:component>
</template>
`;
expect(() =>
transformSync(template, 'foo.html', {
enableDynamicComponents: false,
...TRANSFORMATION_OPTIONS,
})
).toThrow('LWC1187: Invalid lwc:is usage');
});

// TODO [#3331]: remove usage of lwc:dynamic in 246
it('should allow deprecated dynamic components when experimentalDynamicDirective is set to true', () => {
const template = `
<template>
<x-dynamic lwc:dynamic={ctor}></x-dynamic>
</template>
`;
const { code, warnings } = transformSync(template, 'foo.html', {
experimentalDynamicDirective: true,
...TRANSFORMATION_OPTIONS,
});

expect(warnings).toHaveLength(1);
expect(warnings?.[0]).toMatchObject({
message: expect.stringContaining('lwc:dynamic directive is deprecated'),
});
expect(code).toContain('api_deprecated_dynamic_component');
});

// TODO [#3331]: remove usage of lwc:dynamic in 246
it('should not allow dynamic components when experimentalDynamicDirective is set to false', () => {
const template = `
<template>
<x-dynamic lwc:dynamic={ctor}></x-dynamic>
</template>
`;
expect(() =>
transformSync(template, 'foo.html', {
experimentalDynamicDirective: false,
...TRANSFORMATION_OPTIONS,
})
).toThrowErrorMatchingInlineSnapshot(
'"LWC1128: Invalid lwc:dynamic usage. The LWC dynamic Directive must be enabled in order to use this feature."'
);
});
});
4 changes: 2 additions & 2 deletions packages/@lwc/compiler/src/transformers/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default function scriptTransform(
): TransformResult {
const {
isExplicitImport,
experimentalDynamicComponent: dynamicImports,
dynamicImportConfig: dynamicImports,
outputConfig: { sourcemap },
} = options;

Expand All @@ -36,7 +36,7 @@ export default function scriptTransform(
babelrc: false,
configFile: false,

// Force Babel to generate new line and whitespaces. This prevent Babel from generating
// Force Babel to generate new line and white spaces. This prevent Babel from generating
// an error when the generated code is over 500KB.
compact: false,

Expand Down
9 changes: 7 additions & 2 deletions packages/@lwc/compiler/src/transformers/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,29 @@ export default function templateTransform(
options: NormalizedTransformOptions
): TransformResult {
const {
experimentalDynamicComponent,
dynamicImportConfig,
preserveHtmlComments,
enableStaticContentOptimization,
customRendererConfig,
enableLwcSpread,
enableScopedSlots,
enableDynamicComponents,
// TODO [#3331]: remove usage of lwc:dynamic in 246
experimentalDynamicDirective: deprecatedDynamicDirective,
} = options;
const experimentalDynamicDirective = Boolean(experimentalDynamicComponent);
const experimentalDynamicDirective = deprecatedDynamicDirective ?? Boolean(dynamicImportConfig);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lwc:dynamic and lwc:is are two different directives. IMO, they should not affect each other's enablement state.

Copy link
Member Author

@jmsjtu jmsjtu Feb 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left a comment here regarding the flags but changing dynamicImportConfig back to experimentalDynamicComponents.

This is actually in place to preserve existing behavior for downstream consumers. The current behavior is to enable lwc:dynamic if the experimentalDynamicComponents option is provided.

In 244 we want to allow the LCS team to disable access to lwc:dynamic by exposing the experimentalDynamicDirective directly (they can toggle it off).

The Boolean(experimentalDynamicComponent) is to prevent all other downstream consumers like lwc-test from breaking.


let result;
try {
result = compile(src, {
// TODO [#3331]: remove usage of lwc:dynamic in 246
jmsjtu marked this conversation as resolved.
Show resolved Hide resolved
experimentalDynamicDirective,
preserveHtmlComments,
enableStaticContentOptimization,
customRendererConfig,
enableLwcSpread,
enableScopedSlots,
enableDynamicComponents,
});
} catch (e) {
throw normalizeToCompilerError(TransformerErrors.HTML_TRANSFORMER_ERROR, e, { filename });
Expand Down
38 changes: 35 additions & 3 deletions packages/@lwc/engine-core/src/framework/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -533,9 +533,11 @@ function fid(url: string | undefined | null): string | null | undefined {
}

/**
* create a dynamic component via `<x-foo lwc:dynamic={Ctor}>`
* [ddc] - create a (deprecated) dynamic component via `<x-foo lwc:dynamic={Ctor}>`
*
* TODO [#3331]: remove usage of lwc:dynamic in 246
*/
function dc(
function ddc(
pmdartus marked this conversation as resolved.
Show resolved Hide resolved
sel: string,
Ctor: LightningElementConstructor | null | undefined,
data: VElementData,
Expand All @@ -550,7 +552,7 @@ function dc(
);
}
// null or undefined values should produce a null value in the VNodes
if (Ctor == null) {
if (isNull(Ctor) || isUndefined(Ctor)) {
return null;
}
if (!isComponentConstructor(Ctor)) {
Expand All @@ -560,6 +562,35 @@ function dc(
return c(sel, Ctor, data, children);
}

/**
* [dc] - create a dynamic component via `<lwc:component lwc:is={Ctor}>`
*/
function dc(
Ctor: LightningElementConstructor | null | undefined,
data: VElementData,
children: VNodes = EmptyArray
): VCustomElement | null {
if (process.env.NODE_ENV !== 'production') {
assert.isTrue(isObject(data), `dc() 2nd argument data must be an object.`);
assert.isTrue(
arguments.length === 3 || isArray(children),
`dc() 3rd argument data must be an array.`
);
}
// null or undefined values should produce a null value in the VNodes
if (isNull(Ctor) || isUndefined(Ctor)) {
return null;
}

if (!isComponentConstructor(Ctor)) {
throw new Error(
`Invalid constructor ${toString(Ctor)} is not a LightningElement constructor.`
);
}

return null;
}
Comment on lines +568 to +592
Copy link
Member Author

@jmsjtu jmsjtu Feb 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a dummy implementation and is not how the function is designed to work. The implementation can be found in part 2, here.

This is only added here because the template compiler will call the dc function for the new dynamic components syntax (<lwc:component lwc:is={}>)


/**
* slow children collection marking mechanism. this API allows the compiler to signal
* to the engine that a particular collection of children must be diffed using the slow
Expand Down Expand Up @@ -628,6 +659,7 @@ const api = ObjectFreeze({
fid,
shc,
ssf,
ddc,
});

export default api;
Expand Down
7 changes: 6 additions & 1 deletion packages/@lwc/engine-server/src/__tests__/fixtures.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import fs from 'fs';
import path from 'path';

import { rollup } from 'rollup';
import { rollup, RollupWarning } from 'rollup';
// @ts-ignore
import lwcRollupPlugin from '@lwc/rollup-plugin';
import { isVoidElement, HTML_NAMESPACE } from '@lwc/shared';
Expand All @@ -29,6 +29,8 @@ jest.setTimeout(10_000 /* 10 seconds */);
async function compileFixture({ input, dirname }: { input: string; dirname: string }) {
const modulesDir = path.resolve(dirname, './modules');
const outputFile = path.resolve(dirname, './dist/compiled.js');
// TODO [#3331]: this is only needed to silence warnings on lwc:dynamic, remove in 246.
const warnings: RollupWarning[] = [];

const bundle = await rollup({
input,
Expand All @@ -43,6 +45,9 @@ async function compileFixture({ input, dirname }: { input: string; dirname: stri
],
}),
],
onwarn(warning) {
warnings.push(warning);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would recommend checking whether or not the warning is related to lwc:dynamic before silencing it. Swallowing all the errors might hide some unexpected behavior in tests.

},
});

await bundle.write({
Expand Down
2 changes: 1 addition & 1 deletion packages/@lwc/errors/src/compiler/error-info/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
/**
* Next error code: 1183
* Next error code: 1189
*/

export * from './compiler';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ export const ParserDiagnostics = {
LWC_INNER_HTML_INVALID_CUSTOM_ELEMENT: {
code: 1140,
message:
'Invalid lwc:inner-html usage on element "{0}". The directive can\'t be used on a custom element.',
'Invalid lwc:inner-html usage on element "{0}". The directive can\'t be used on a custom element or special LWC managed elements denoted with lwc:*.',
level: DiagnosticLevel.Error,
url: '',
},
Expand Down Expand Up @@ -846,4 +846,49 @@ export const ParserDiagnostics = {
level: DiagnosticLevel.Warning,
url: '',
},

LWC_COMPONENT_TAG_WITHOUT_IS_DIRECTIVE: {
code: 1183,
message: `<lwc:component> must have an 'lwc:is' attribute.`,

This comment was marked as resolved.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read this as "an ell" so I think it's fine to say an.

level: DiagnosticLevel.Error,
url: '',
},

UNSUPPORTED_LWC_TAG_NAME: {
code: 1184,
message: '{0} is not a special LWC tag name and will be treated as an HTML element.',

This comment was marked as resolved.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here. I know some Anglophones say "haitch" for "H", but "aitch" is more common AFAIK.

level: DiagnosticLevel.Warning,
url: '',
},

INVALID_LWC_IS_DIRECTIVE_VALUE: {
code: 1185,
message:
'Invalid lwc:is usage for value {0}. The value assigned to lwc:is must be an expression.',
level: DiagnosticLevel.Error,
url: '',
},

LWC_IS_INVALID_ELEMENT: {
code: 1186,
message:
'Invalid lwc:is usage for element {0}. The directive can only be used with <lwc:component>',
level: DiagnosticLevel.Error,
url: '',
},

INVALID_OPTS_LWC_ENABLE_DYNAMIC_COMPONENTS: {
code: 1187,
message:
'Invalid lwc:is usage. The LWC dynamic Directive must be enabled in order to use this feature.',
jmsjtu marked this conversation as resolved.
Show resolved Hide resolved
level: DiagnosticLevel.Error,
url: '',
},

DEPRECATED_LWC_DYNAMIC_ATTRIBUTE: {
code: 1188,
message: `The lwc:dynamic directive is deprecated and will be removed in a future release. Please use lwc:is instead.`,
level: DiagnosticLevel.Warning,
url: '',
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ async function getCompiledModule(dirName) {
dir: dirName,
},
],
experimentalDynamicComponent: {
dynamicImportConfig: {
loader: 'test-utils',
strict: true,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function createPreprocessor(config, emitter, logger) {
const plugins = [
lwcRollupPlugin({
sourcemap: true,
experimentalDynamicComponent: {
dynamicImportConfig: {
loader: 'test-utils',
strict: true,
},
Expand Down
4 changes: 3 additions & 1 deletion packages/@lwc/rollup-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ export default {
- `modules` (type: `ModuleRecord[]`, default: `[]`) - The [module resolution](https://lwc.dev/guide/es_modules#module-resolution) overrides passed to the `@lwc/module-resolver`.
- `stylesheetConfig` (type: `object`, default: `{}`) - The stylesheet compiler configuration to pass to the `@lwc/style-compiler`.
- `preserveHtmlComments` (type: `boolean`, default: `false`) - The configuration to pass to the `@lwc/template-compiler`.
- `experimentalDynamicComponent` (type: `DynamicComponentConfig`, default: `null`) - The configuration to pass to `@lwc/compiler`.
- `dynamicImportConfig` (type: `DynamicImportConfig`, default: `null`) - The configuration to pass to `@lwc/compiler`.
- `experimentalDynamicDirective` (type: `boolean`, default: `false`) - The configuration to pass to `@lwc/template-compiler` to enable deprecated dynamic components.
- `enableDynamicComponents` (type: `boolean`, default: `false`) - The configuration to pass to `@lwc/template-compiler` to enable dynamic components.
- `enableLwcSpread` (type: `boolean`, default: `false`) - The configuration to pass to the `@lwc/template-compiler`.
- `enableScopedSlots` (type: `boolean`, default: `false`) - The configuration to pass to `@lwc/template-compiler` to enable scoped slots feature.
- `disableSyntheticShadowSupport` (type: `boolean`, default: `false`) - Set to true if synthetic shadow DOM support is not needed, which can result in smaller output.
Loading