How to use @babel/code-frame - 10 common examples

To help you get started, we’ve selected a few @babel/code-frame 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 fabiomcosta / mvjs / src / log.js View on Github external
function createFrame({file, loc}: LogOptions = {}): string {
  if (!file) {
    return '';
  }
  // The column location seems off by one, fixing that.
  if (loc) {
    loc.start.column++;
    loc.end.column++;
  }
  const frame = codeFrameColumns(file.source, loc, {highlightCode: true, forceColor: true});
  return `\nat ${file.path}:\n${frame}`;
}
github RokuRoad / bright / test / helpers.ts View on Github external
export const error = ({ message, location }, source: string): string => {
  return codeFrameColumns(source, location, { highlightCode: true, message })
}
github PassFort / json-schema-to-flow-type / src / __tests__ / FlowTypeGenerator.spec.js View on Github external
try {
    return babylon.parse(code, {
      sourceType: 'module',
      plugins: [
        'flow',
      ]
    });
  } catch(err) {
    if (!(err instanceof SyntaxError)) {
      throw err;
    }

    const posData = err.message.match(/ \((\d+):(\d+)\)$/);

    if (posData !== null) {
      err.message += `\n${codeFrame(code, ...posData.slice(1, 3))}`;
    }

    throw err;
  }
};
github preconstruct / preconstruct / packages / cli / src / rollup-plugins / terser.ts View on Github external
.catch((error: any) => {
          const { message, line, col: column } = error;
          console.error(
            codeFrameColumns(code, { start: { line, column } }, { message })
          );
          throw error;
        });
github facebook / create-react-app / packages / react-dev-utils / typescriptFormatter.js View on Github external
severity: message.getSeverity(),
          file: message.getFile(),
          line: message.getLine(),
          content: message.getContent(),
          code: message.getCode(),
          character: message.getCharacter(),
        }
      : message;

  const colors = new chalk.Instance({ enabled: useColors });
  const messageColor = message.isWarningSeverity() ? colors.yellow : colors.red;
  const fileAndNumberColor = colors.bold.cyan;

  const source = file && fs.existsSync(file) && fs.readFileSync(file, 'utf-8');
  const frame = source
    ? codeFrame(
        source,
        { start: { line: line, column: character } },
        { highlightCode: useColors }
      )
        .split('\n')
        .map(str => '  ' + str)
        .join(os.EOL)
    : '';

  return [
    messageColor.bold(`${types[type]} ${severity.toLowerCase()} in `) +
      fileAndNumberColor(`${file}(${line},${character})`) +
      messageColor(':'),
    content +
      '  ' +
      messageColor.underline((type === 'lint' ? 'Rule: ' : 'TS') + code),
github expo / json-file / src / JsonFile.js View on Github external
} else {
      return defaultValue;
    }
  }
  try {
    if (_getOption(options, 'json5')) {
      return JSON5.parse(json);
    } else {
      return JSON.parse(json);
    }
  } catch (e) {
    let defaultValue = jsonParseErrorDefault(options);
    if (defaultValue === undefined) {
      let location = locationFromSyntaxError(e, json);
      if (location) {
        let codeFrame = codeFrameColumns(json, { start: location });
        e.codeFrame = codeFrame;
        e.message += `\n${codeFrame}`;
      }
      throw new JsonFileError(`Error parsing JSON file: ${file}`, e, 'EJSONPARSE');
    } else {
      return defaultValue;
    }
  }
}
github gatsbyjs / gatsby / packages / gatsby / src / query / file-parser.js View on Github external
},
        }
      } else if (err instanceof EmptyGraphQLTagError) {
        const location = err.templateLoc
          ? {
              start: err.templateLoc.start,
              end: err.templateLoc.end,
            }
          : null

        structuredError = {
          id: `85917`,
          location,
          context: {
            codeFrame: location
              ? codeFrameColumns(text, location, {
                  highlightCode: process.env.FORCE_COLOR !== `0`,
                })
              : null,
          },
        }
      } else if (err instanceof GraphQLSyntaxError) {
        const location = {
          start: locInGraphQlToLocInFile(
            err.templateLoc,
            err.originalError.locations[0]
          ),
        }

        structuredError = {
          id: `85918`,
          location,
github cypress-io / cypress / packages / driver / src / cypress / stack_utils.js View on Github external
const getCodeFrameFromSource = (sourceCode, { line, column, relativeFile, absoluteFile }) => {
  if (!sourceCode) return

  const frame = codeFrameColumns(sourceCode, { start: { line, column } })

  if (!frame) return

  return {
    line,
    column,
    relativeFile,
    absoluteFile,
    frame,
    language: getLanguageFromExtension(relativeFile),
  }
}
github Tencent / omi / packages / omip / taro-transformer-wx / src / utils.ts View on Github external
export function codeFrameError (node, msg: string) {
  let errMsg = ''
  try {
    errMsg = codeFrameColumns(setting.sourceCode, node && node.type && node.loc ? node.loc : node, {
      highlightCode: true
    })
  } catch (error) {
    errMsg = 'failed to locate source'
  }
  return new Error(`${msg}
-----
${errMsg}`)
}
github reduxjs / redux-devtools / packages / redux-devtools-trace-monitor / src / react-error-overlay / containers / StackFrameCodeBlock.js View on Github external
if (m && m[0]) {
      whiteSpace = Math.min(whiteSpace, m[0].length);
    } else {
      whiteSpace = 0;
    }
  });
  lines.forEach(function(e) {
    let { content: text } = e;
    const { lineNumber: line } = e;

    if (isFinite(whiteSpace)) {
      text = text.substring(whiteSpace);
    }
    sourceCode[line - 1] = text;
  });
  const ansiHighlight = codeFrameColumns(
    sourceCode.join('\n'),
    {
      start: {
        line: lineNum,
        column:
          columnNum == null
            ? 0
            : columnNum - (isFinite(whiteSpace) ? whiteSpace : 0),
      },
    },
    {
      forceColor: true,
      linesAbove: contextSize,
      linesBelow: contextSize,
    }
  );

@babel/code-frame

Generate errors that contain a code frame that point to source locations.

MIT
Latest version published 18 days ago

Package Health Score

95 / 100
Full package analysis

Popular @babel/code-frame functions

Similar packages