main
js 74 lines 2.2 KB
Raw
1 import {
2 resolve,
3 load as reactLoad,
4 getSource as getSourceImpl,
5 transformSource as reactTransformSource,
6 } from 'react-server-dom-unbundled/node-loader';
7
8 export {resolve};
9
10 import babel from '@babel/core';
11
12 const babelOptions = {
13 babelrc: false,
14 ignore: [/\/(build|node_modules)\//],
15 plugins: [
16 '@babel/plugin-syntax-import-meta',
17 ['@babel/plugin-transform-react-jsx', {runtime: 'automatic'}],
18 ],
19 sourceMaps: process.env.NODE_ENV === 'development' ? 'inline' : false,
20 };
21
22 async function babelLoad(url, context, defaultLoad) {
23 const {format} = context;
24 const result = await defaultLoad(url, context, defaultLoad);
25 if (result.format === 'module') {
26 const opt = Object.assign({filename: url}, babelOptions);
27 const newResult = await babel.transformAsync(result.source, opt);
28 if (!newResult) {
29 if (typeof result.source === 'string') {
30 return result;
31 }
32 return {
33 source: Buffer.from(result.source).toString('utf8'),
34 format: 'module',
35 };
36 }
37 return {source: newResult.code, format: 'module'};
38 }
39 return defaultLoad(url, context, defaultLoad);
40 }
41
42 export async function load(url, context, defaultLoad) {
43 return await reactLoad(url, context, (u, c) => {
44 return babelLoad(u, c, defaultLoad);
45 });
46 }
47
48 async function babelTransformSource(source, context, defaultTransformSource) {
49 const {format} = context;
50 if (format === 'module') {
51 const opt = Object.assign({filename: context.url}, babelOptions);
52 const newResult = await babel.transformAsync(source, opt);
53 if (!newResult) {
54 if (typeof source === 'string') {
55 return {source};
56 }
57 return {
58 source: Buffer.from(source).toString('utf8'),
59 };
60 }
61 return {source: newResult.code};
62 }
63 return defaultTransformSource(source, context, defaultTransformSource);
64 }
65
66 async function transformSourceImpl(source, context, defaultTransformSource) {
67 return await reactTransformSource(source, context, (s, c) => {
68 return babelTransformSource(s, c, defaultTransformSource);
69 });
70 }
71
72 export const transformSource =
73 process.version < 'v16' ? transformSourceImpl : undefined;
74 export const getSource = process.version < 'v16' ? getSourceImpl : undefined;