MCPcopy Create free account
hub / github.com/freeCodeCamp/freeCodeCamp / transformScript

Function transformScript

packages/challenge-builder/src/transformers.js:220–255  ·  view source on GitHub ↗
(documentElement, { useModules })

Source from the content-addressed store, hash-verified

218}
219
220async function transformScript(documentElement, { useModules }) {
221 await loadBabel();
222 await loadPresetEnv();
223 await loadPresetReact();
224 const scriptTags = documentElement.querySelectorAll('script');
225 scriptTags.forEach(script => {
226 const isBabel = script.type === 'text/babel';
227 const hasSource = !!script.src;
228 // TODO: make the use of JSX conditional on more than just the script type.
229 // It should only be used for React challenges since it would be confusing
230 // for learners to see the results of a transformation they didn't ask for.
231 const baseOptions = isBabel ? presetsJSX : presetsJS;
232
233 const options = {
234 ...baseOptions,
235 ...(useModules && { plugins: [MODULE_TRANSFORM_PLUGIN] })
236 };
237
238 // The type has to be removed, otherwise the browser will ignore the script.
239 // However, if we're importing modules, the type will be removed when the
240 // scripts are embedded in the HTML.
241 if (isBabel && !useModules) script.removeAttribute('type');
242 // We could use babel standalone to transform inline code in the preview,
243 // but that generates a warning that's shown to learner. By removing the
244 // type attribute and transforming the code we can avoid that warning.
245 if (isBabel && !hasSource) {
246 script.removeAttribute('type');
247 script.setAttribute('data-type', 'text/babel');
248 }
249
250 // Skip unnecessary transformations
251 script.innerHTML = script.innerHTML
252 ? babelTransformCode(options)(script.innerHTML)
253 : '';
254 });
255}
256
257const deferScript = scriptCode => {
258 // Mimic the behavior of a defer script by waiting until the DOM is loaded

Callers 1

transformFunction · 0.85

Calls 4

loadBabelFunction · 0.85
loadPresetEnvFunction · 0.85
loadPresetReactFunction · 0.85
babelTransformCodeFunction · 0.85

Tested by

no test coverage detected