diff --git a/utils/rollup-build-target.mjs b/utils/rollup-build-target.mjs index 2653a7d3ade..1530b3b250e 100644 --- a/utils/rollup-build-target.mjs +++ b/utils/rollup-build-target.mjs @@ -11,6 +11,7 @@ import { visualizer } from 'rollup-plugin-visualizer'; import { shaderChunks } from './rollup-shader-chunks.mjs'; import { engineLayerImportValidation } from './rollup-import-validation.mjs'; import { spacesToTabs } from './rollup-spaces-to-tabs.mjs'; +import { dynamicImportTransform } from './rollup-dynamic-import-transform.mjs'; import { version, revision } from './rollup-version-revision.mjs'; import { getBanner } from './rollup-get-banner.mjs'; @@ -177,6 +178,7 @@ function buildTarget(buildType, moduleFormat, input = 'src/index.js', buildDir = output: outputOptions, plugins: [ jscc(jsccParam), + moduleFormat === 'es5' ? dynamicImportTransform() : undefined, shaderChunks({ enabled: buildType !== 'debug' }), engineLayerImportValidation(input, buildType === 'debug'), buildType !== 'debug' ? strip(stripOptions) : undefined, diff --git a/utils/rollup-dynamic-import-transform.mjs b/utils/rollup-dynamic-import-transform.mjs new file mode 100644 index 00000000000..20a08851ee2 --- /dev/null +++ b/utils/rollup-dynamic-import-transform.mjs @@ -0,0 +1,25 @@ +/** + * This rollup plugin transform code with dynamic import statements and wraps them + * in a `new Function('import("modulePath")')` statement, in order to avoid parsing errors in older browsers + * without support for dynamic imports. + * + * Note that whilst this will prevent parsing errors, it can trigger CSP errors. + */ + +export function dynamicImportTransform() { + return { + name: 'dynamic-import-transform', + transform(code, id) { + /** + * Transforms the code by replacing `import(` with `new Function("return import")(`. + * @param {string} code - The code to transform. + * @param {string} id - The id of the code. + * @returns {object} - The transformed code and map. + */ + return { + code: code.replace(/([^\w])import\(/g, '$1new Function("modulePath", "return import(modulePath)")('), + map: null + }; + } + }; +}