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

Add rollup import transform #6090

Merged
merged 4 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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: 2 additions & 0 deletions utils/rollup-build-target.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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,
Expand Down
25 changes: 25 additions & 0 deletions utils/rollup-dynamic-import-transform.mjs
Original file line number Diff line number Diff line change
@@ -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(/import\(/g, 'new Function("modulePath", "return import(modulePath)")('),
kpal81xd marked this conversation as resolved.
Show resolved Hide resolved
marklundin marked this conversation as resolved.
Show resolved Hide resolved
map: null
};
}
};
}