@babel/core#transformAsync TypeScript Examples
The following examples show how to use
@babel/core#transformAsync.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: non-plugin-script.ts From fect with MIT License | 6 votes |
_transformScript = async (stdin: string, id: string) => {
let code = replaceStyleInJs(stdin)
if (isJsx(id)) {
const res = await transformAsync(code, { filename: id })
;({ code } = res)
}
const esbuildResult = await esbuildTransform(code, {
loader: 'ts',
target: 'es2016',
format: process.env.BABEL_ENV === 'esmodule' ? 'esm' : 'cjs'
})
return {
code: esbuildResult.code
}
}
Example #2
Source File: babelTransform.ts From web with MIT License | 6 votes |
export async function babelTransform(filename: string, source: string, config: TransformOptions) {
const largeFile = source.length > 100000;
const result = await transformAsync(source, {
filename,
// prevent generating pretty output for large files
compact: largeFile,
// babel runs out of memory when processing source maps andfor large files
sourceMaps: !largeFile,
...config,
});
if (!result || typeof result.code !== 'string') {
throw new Error('Failed to transform');
}
return result.code;
}
Example #3
Source File: transformMdxToCsf.ts From web with MIT License | 6 votes |
export async function transformMdxToCsf(body: string, filePath: string): Promise<string> {
// turn MDX to JSX
const jsx = `
import { React, mdx } from '@web/storybook-prebuilt/web-components.js';
${await mdx(body, { compilers, filepath: filePath })}
`;
// turn JSX to JS
const babelResult = await transformAsync(jsx, {
filename: filePath,
sourceMaps: true,
plugins: [require.resolve('@babel/plugin-transform-react-jsx')],
});
if (!babelResult?.code) {
throw createError(`Something went wrong while transforming ${filePath}`);
}
// rewrite imports
let result = babelResult.code.replace(
/@storybook\/addon-docs\/blocks/g,
'@web/storybook-prebuilt/addon-docs/blocks.js',
);
result = result.replace(
/@storybook\/addon-docs/g,
'@web/storybook-prebuilt/addon-docs/blocks.js',
);
return result;
}
Example #4
Source File: createPolyfillsLoader.ts From web with MIT License | 5 votes |
/**
* Creates a loader script that executes immediately, loading the configured
* polyfills and resources (app entrypoints, scripts etc.).
*/
export async function createPolyfillsLoader(
cfg: PolyfillsLoaderConfig,
): Promise<PolyfillsLoader | null> {
let polyfillFiles = await createPolyfillsData(cfg);
const coreJs = polyfillFiles.find(pf => pf.name === 'core-js');
polyfillFiles = polyfillFiles.filter(pf => pf !== coreJs);
const { loadPolyfillsCode, generatedFiles } = createPolyfillsLoaderCode(cfg, polyfillFiles);
let code = `
${createLoadScriptCode(cfg, polyfillFiles)}
${loadPolyfillsCode}
${createLoadFilesCode(cfg, polyfillFiles)}
`;
if (coreJs) {
generatedFiles.push({
type: fileTypes.SCRIPT,
path: coreJs.path,
content: coreJs.content,
});
// if core-js should be polyfilled, load it first and then the rest because most
// polyfills rely on things like Promise to be already loaded
code = `(function () {
function polyfillsLoader() {
${code}
}
if (${coreJs.test}) {
var s = document.createElement('script');
function onLoaded() {
document.head.removeChild(s);
polyfillsLoader();
}
s.src = "./${relativePolyfillPath(coreJs.path, cfg)}";
s.onload = onLoaded;
s.onerror = function () {
console.error('[polyfills-loader] failed to load: ' + s.src + ' check the network tab for HTTP status.');
onLoaded();
}
document.head.appendChild(s);
} else {
polyfillsLoader();
}
})();`;
} else {
code = `(function () { ${code} })();`;
}
if (cfg.minify) {
const output = await Terser.minify(code);
if (!output || !output.code) {
throw new Error('Could not minify loader.');
}
({ code } = output);
} else {
const output = await transformAsync(code, { babelrc: false, configFile: false });
if (!output || !output.code) {
throw new Error('Could not prettify loader.');
}
({ code } = output);
}
if (cfg.externalLoaderScript) {
generatedFiles.push({ type: 'script', path: 'loader.js', content: code });
}
return { code, polyfillFiles: generatedFiles };
}
Example #5
Source File: babel.test.ts From react-loosely-lazy with Apache License 2.0 | 4 votes |
describe.each(['server', 'client'])('on the %s', (env: string) => {
type BabelOptions = Partial<{ filename: string }> & BabelPluginOptions;
const babel = (
code: string,
{ filename = 'test.js', ...options }: BabelOptions = {}
) =>
transformAsync(code, {
babelrc: false,
caller: {
name: 'tests',
supportsStaticESM: true,
},
configFile: false,
filename,
plugins: [[plugin, { client: env === 'client', ...options }]],
sourceType: 'module',
});
describe('correctly generates the moduleId when running babel from a different cwd', () => {
const transformedImport = env === 'client' ? 'import' : 'require';
const mockCwd = (cwd: string) => {
jest.spyOn(process, 'cwd').mockImplementation(() => cwd);
};
afterEach(() => {
jest.restoreAllMocks();
});
it('by default', async () => {
const mocksDir = join(__dirname, '__mocks__');
// Pretend we are running babel from the __mocks__/test directory
mockCwd(join(mocksDir, 'test'));
await expect(
babel(
`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(() => import('./async'));
`,
{
// Pretend the file being transpiled is in the __mocks__/app directory
filename: join(mocksDir, 'app', 'index.js'),
}
)
).resolves.toMatchObject({
code: outdent`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(() => ${transformedImport}('./async'), {
moduleId: "../app/async.js"
});
`,
});
});
it('when given a modulePathReplacer', async () => {
const mocksDir = join(__dirname, '__mocks__');
// Pretend we are running babel from the __mocks__/test directory
mockCwd(join(mocksDir, 'test'));
await expect(
babel(
`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(() => import('./async'));
`,
{
// Pretend the file being transpiled is in the __mocks__/app directory
filename: join(mocksDir, 'app', 'index.js'),
// Since babel is running in the test directory, but the file and its import live in the app directory we
// want to transform the moduleId so that it matches where the app directory actually lives
modulePathReplacer: {
from: '../',
to: './',
},
}
)
).resolves.toMatchObject({
code: outdent`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(() => ${transformedImport}('./async'), {
moduleId: "./app/async.js"
});
`,
});
});
});
describe('throws an error when the loader argument', () => {
it('is not a function', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint({});
`)
).rejects.toThrow('Loader argument must be a function');
});
it('is an async function with a default import', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(
async () => await import('react'),
{ ssr: true },
);
`)
).rejects.toThrow('Loader argument does not support await expressions');
});
it('is an async function with a named import', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(
async () => {
const { Component } = await import('react');
return Component;
},
{ ssr: true },
);
`)
).rejects.toThrow('Loader argument does not support await expressions');
});
it('uses a default import with Promise.prototype.then onRejected argument', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(() =>
import('react').then(Component => Component, () => {})
);
`)
).rejects.toThrow(
'Loader argument does not support Promise.prototype.then with more than one argument'
);
});
it('uses a named import with Promise.prototype.then onRejected argument', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(() =>
import('react').then(({ Component }) => Component, () => {})
);
`)
).rejects.toThrow(
'Loader argument does not support Promise.prototype.then with more than one argument'
);
});
it('uses a default import with Promise.prototype.catch', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(() =>
import('react').catch(() => {})
);
`)
).rejects.toThrow(
'Loader argument does not support Promise.prototype.catch'
);
});
it('uses a named import with Promise.prototype.catch', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(() =>
import('react')
.then(({ Component }) => Component)
.catch(() => {})
);
`)
).rejects.toThrow(
'Loader argument does not support Promise.prototype.catch'
);
});
});
describe('throws an error when the options argument', () => {
it('uses a SpreadElement', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const opts = {};
const TestComponent = lazyForPaint(
() => import('react'),
{
...opts,
ssr: true,
},
);
`)
).rejects.toThrow(
'Options argument does not support SpreadElement as it is not statically analyzable'
);
});
it('ssr option is an ObjectProperty with an Expression value', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(
() => import('react'),
{
ssr: () => {
return true;
},
},
);
`)
).rejects.toThrow('Unable to statically analyze ssr option');
});
it('ssr option is an ObjectMethod', async () => {
await expect(
babel(`
import { lazyForPaint } from 'react-loosely-lazy';
const TestComponent = lazyForPaint(
() => import('react'),
{
get ssr() {
return true;
},
},
);
`)
).rejects.toThrow('Unable to statically analyze ssr option');
});
});
});