How to use sucrase - 10 common examples

To help you get started, we’ve selected a few sucrase examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github powercord-org / powercord / src / Powercord / modules / jsx.js View on Github external
require.extensions['.jsx'] = (_module, filename) => {
    const source = readFileSync(filename, 'utf8');
    const hash = checksum(`/* sucrase-jsx (${sucrase.getVersion()}) | ${filename} */ ${source}`);
    const cached = join(cacheDir, `${hash}.js`);

    try {
      _module._compile(readFileSync(cached, 'utf8'), filename);
    } catch (_) {
      const res = sucrase.transform(source, {
        transforms: [ 'jsx' ],
        filePath: filename
      }).code;

      _module._compile(res, filename);

      writeFile(cached, res, (err) => {
        if (err) {
          console.error('%c[Powercord:JSX]', 'color: #7289da', 'Failed to write to cache');
          console.error(err);
        }
      });
    }
  };
github preactjs / preact-www / src / components / controllers / repl / repl.worker.js View on Github external
export function process(code) {
	code = `${IMPORTS}${code}`;

	if (!code.match(/[\s\b;,]export[{ ]/)) {
		code = code.replace(
			/([\s\b;,])((async )?(function|class)[\s{])/g,
			'$1export default $2'
		);
	}

	let out = {};
	try {
		out = transform(code, {
			filePath: 'repl.js',
			sourceMapOptions: {
				compiledFilename: 'repl.js'
			},
			transforms: ['jsx', 'typescript', 'imports'],
			// omit _jsxSource junk
			production: true,
			// .default fixing since we're using shim modules
			enableLegacyTypeScriptModuleInterop: true,
			enableLegacyBabel5ModuleInterop: true,
			jsxPragma: 'h',
			jsxFragmentPragma: 'Fragment'
		});
	} catch (err) {
		if (err.name !== 'SyntaxError' && /unexpected\stoken/i.test(err.message)) {
			let old = err;
github alangpierce / sucrase / integrations / gulp-plugin / src / index.ts View on Github external
file: any,
    enc: string,
    // tslint:disable-next-line no-any
    cb: (err?: any, data?: any) => void,
  ): void {
    if (file.isNull()) {
      cb(null, file);
      return;
    }
    if (file.isStream()) {
      cb(new PluginError(PLUGIN_NAME, "Streaming is not supported."));
      return;
    }

    try {
      const resultCode = transform(file.contents.toString(), {filePath: file.path, ...options})
        .code;
      file.contents = Buffer.from(resultCode);
      file.path = replaceExt(file.path, ".js");
      this.push(file);
    } catch (e) {
      e.message = `Error when processing file ${file.path}: ${e.message}`;
      this.emit("error", new PluginError(PLUGIN_NAME, e));
    }

    cb();
  });
}
github alangpierce / sucrase / website / src / getTokens.ts View on Github external
export default function getTokens(code: string, transforms: Array): string {
  try {
    return getFormattedTokens(code, {transforms});
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(e);
    return e.message;
  }
}
github WeAreGenki / minna-ui / utils / jest-config / transforms / es.js View on Github external
exports.process = (src, filename) => {
  const transforms = getTransforms(filename);

  if (transforms !== null) {
    const result = transform(src, {
      filePath: filename,
      jsxFragmentPragma: 'Fragment', // Preact style JSX
      jsxPragma: 'h',
      production: true, // Don't add debug attributes to snapshots
      transforms,
    });

    return {
      code: result.code,
      map: result.sourceMap,
    };
  }

  return { code: src, map: '' };
};
github popeindustries / dvlp / lib / utils / file.js View on Github external
if (transpiled) {
          // Ignore async
          if (transpiled instanceof Promise) {
            warn(WARN_SERVER_TRANSPILE);
          } else {
            code = transpiled;
          }
        }
      }

      if (!isModule(code)) {
        return code;
      }

      return sucrase.transform(code, {
        transforms: ['imports'],
        filePath
      }).code;
    },
    {
github alangpierce / sucrase / website / config / env.js View on Github external
function getClientEnvironment(publicUrl) {
  const raw = {
    // Useful for determining whether we’re running in production mode.
    // Most importantly, it switches React into the correct mode.
    NODE_ENV: process.env.NODE_ENV || "development",
    // Useful for resolving the correct path to static assets in `public`.
    // For example, <img src="{process.env.PUBLIC_URL">.
    // This should only be used as an escape hatch. Normally you would put
    // images into the `src` and `import` them in code to get their paths.
    PUBLIC_URL: publicUrl,
    // eslint-disable-next-line global-require
    SUCRASE_VERSION: require("sucrase").getVersion(),
  };
  // Stringify all values so we can feed into Webpack DefinePlugin
  const stringified = {
    "process.env": Object.keys(raw).reduce((env, key) =&gt; {
      env[key] = JSON.stringify(raw[key]);
      return env;
    }, {}),
  };

  return {raw, stringified};
}
github alangpierce / sucrase / integrations / webpack-loader / src / index.ts View on Github external
function loader(code: string): string {
  const webpackRemainingChain = getRemainingRequest(this).split("!");
  const filePath = webpackRemainingChain[webpackRemainingChain.length - 1];
  const options: Options = getOptions(this) as Options;
  return transform(code, {filePath, ...options}).code;
}
github Financial-Times / x-dash / packages / x-node-jsx / index.js View on Github external
const handleJSX = (code) => {
		const transformed = transform(code, options);
		return transformed.code;
	};
github alangpierce / sucrase / integrations / jest-plugin / src / index.ts View on Github external
export function process(src: string, filename: string): string {
  const transforms = getTransforms(filename);
  if (transforms !== null) {
    return transform(src, {transforms, filePath: filename}).code;
  } else {
    return src;
  }
}

sucrase

Super-fast alternative to Babel for when you can target modern JS runtimes

MIT
Latest version published 11 months ago

Package Health Score

82 / 100
Full package analysis