How to use the acorn-jsx function in acorn-jsx

To help you get started, we’ve selected a few acorn-jsx 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 sebastian-software / preppy / src / getRollupInputOptions.js View on Github external
return {
    input,
    cache,
    onwarn: (warning) => {
      console.warn(chalk.red(`  - ${warning.message} [${warning.code}]`))
    },
    external(dependency) {
      // Very simple externalization:
      // We exclude all files from NodeJS resolve basically which are not relative to current file.
      // We also bundle absolute paths, these are just an intermediate step in Rollup resolving files and
      // as we do not support resolving from node_modules (we never bundle these) we only hit this code
      // path for originally local dependencies.
      return !(dependency === input || isRelative(dependency) || isAbsolute(dependency))
    },
    acornInjectPlugins: [ acornJsx() ],
    plugins: [
      options.quiet ? null : progressPlugin({ watch: options.watch }),
      options.exec ? advancedRun() : null,

      typescriptResolvePlugin(),
      rebasePlugin(),
      cjsPlugin({
        include: "node_modules/**",
        extensions
      }),
      replacePlugin(variables),
      jsonPlugin(),
      babelPlugin({
        // Rollup Setting: Prefer usage of a common library of helpers
        runtimeHelpers: format !== "umd",
        // We use envName to pass information about the build target and format to Babel
github storybookjs / storybook / addons / docs / src / frameworks / react / inspection / acornParser.ts View on Github external
InspectionUnknown,
  InspectionIdentifier,
  InspectionArray,
} from './types';

interface ParsingResult {
  inferedType: T;
  ast: any;
}

const ACORN_WALK_VISITORS = {
  ...acornWalk.base,
  JSXElement: () => {},
};

const acornParser = Parser.extend(jsx());

// Cannot use "estree.Identifier" type because this function also support "JSXIdentifier".
function extractIdentifierName(identifierNode: any) {
  return !isNil(identifierNode) ? identifierNode.name : null;
}

function parseIdentifier(identifierNode: estree.Identifier): ParsingResult {
  return {
    inferedType: {
      type: InspectionType.IDENTIFIER,
      identifier: extractIdentifierName(identifierNode),
    },
    ast: identifierNode,
  };
}
github LANIF-UI / dva-boot-desktop / src / routes / Route / model / index.js View on Github external
function getColumnsData(path) {
  if (existsSync(path)) {
    const file = readFileSync(path).toString();
    const ast = acorn.Parser.extend(jsx()).parse(file, {
      sourceType: 'module',
      plugins: {
        stage3: true,
        jsx: true
      }
    });
    // column table search form
    const columnData = [];
    try {
      walk.simple(ast, {
        ObjectExpression(node) {
          const data = {};
          if (node.properties.length) {
            const properties = node.properties.filter(
              item =>
                item.key.name === 'title' ||
github styleguidist / react-styleguidist / src / loaders / utils / getImports.js View on Github external
export default function getImports(code: string): string[] {
	// Parse example source code, but ignore errors:
	// 1. Adjacent JSX elements must be wrapped in an enclosing tag () -
	//    imports/requires are not allowed in this case, and we'll wrap the code
	//    in React.Fragment on the frontend
	// 2. All other errors - we'll deal with them on the frontend
	const ast = getAst(code, [acornJsx()]);
	if (!ast) {
		return [];
	}

	const imports = [];
	walk(ast, {
		enter: node => {
			// import foo from 'foo'
			// import 'foo'
			if (node.type === 'ImportDeclaration') {
				if (node.source) {
					imports.push(node.source.value);
				}
			}

			// require('foo')
github LANIF-UI / dva-boot-desktop / src / routes / CreateRoute / model / index.js View on Github external
*getParentRoutes({ payload }, { call, put, select }) {
      const global = yield select(state => state.global);
      const { currentProject } = global;
      // 解析出column
      const rootRoute = join(
        currentProject.directoryPath,
        'src',
        'routes',
        'index.js'
      );
      const file = readFileSync(rootRoute).toString();
      const ast = acorn.Parser.extend(jsx()).parse(file, {
        ranges: true,
        onComment: comments,
        onToken: tokens,
        sourceType: 'module',
        plugins: {
          stage3: true,
          jsx: true
        }
      });

      const parentRoutes = [];
      try {
        walk.simple(ast, {
          ObjectExpression(node) {
            const data = {};
            if (node.properties.length) {
github remaxjs / remax / packages / remax-cli / src / build / rollupConfig.ts View on Github external
);
  }

  let config: RollupOptions = {
    treeshake: process.env.NODE_ENV === 'production',
    input: [entries.app, ...entries.pages.map(p => p.file), ...entries.images],
    output: {
      dir: options.output,
      format: adapter.moduleFormat,
      exports: 'named',
      sourcemap: false,
      extend: true,
    },
    preserveModules: true,
    preserveSymlinks: true,
    acornInjectPlugins: [jsx()],
    /* istanbul ignore next */
    onwarn(warning, warn) {
      if ((warning as RollupWarning).code === 'THIS_IS_UNDEFINED') return;
      if ((warning as RollupWarning).code === 'CIRCULAR_DEPENDENCY') {
        output('⚠️ 检测到循环依赖,如果不影响项目运行,请忽略', 'yellow');
      }

      if (!warning.message) {
        output(
          `⚠️ ${warning.code}:${warning.plugin || ''} ${(warning as any).text}`,
          'yellow'
        );
      } else {
        output('⚠️ ' + warning.toString(), 'yellow');
      }
    },
github i18next / i18next-scanner / test / jsx-parser.js View on Github external
const jsxToString = (code) => {
    try {
        const ast = Parser.extend(jsx()).parse(`${code}`);

        const nodes = ensureArray(_get(ast, 'body[0].expression.children'));
        if (nodes.length === 0) {
            return '';
        }

        return nodesToString(nodes);
    } catch (e) {
        console.error(e);
        return '';
    }
};
github LANIF-UI / dva-boot-desktop / src / routes / CreateProject / model / index.js View on Github external
function deleteExampleRoute(path) {
  const file = readFileSync(path).toString();
  const ast = acorn.Parser.extend(jsx()).parse(file, {
    ranges: true,
    onComment: comments,
    onToken: tokens,
    sourceType: 'module',
    plugins: {
      stage3: true,
      jsx: true
    }
  });
  try {
    escodegen.attachComments(ast, comments, tokens);
    walk.simple(ast, {
      Program(node) {
        const excludes = [
          './Pages/404',
          './Login',
github LANIF-UI / dva-boot-desktop / src / routes / Route / model / index.js View on Github external
function updateRouteConfig(route, rootRoutePath) {
  const pathReg = /src\\routes(.*)\\index.js/;
  const result = pathReg.exec(route.path);
  let source = '';
  if (result && result.length === 2) {
    source = '.' + result[1].replace(/\\/g, '/');
  }

  const file = readFileSync(rootRoutePath).toString();
  const ast = acorn.Parser.extend(jsx()).parse(file, {
    ranges: true,
    onComment: comments,
    onToken: tokens,
    sourceType: 'module',
    plugins: {
      stage3: true,
      jsx: true
    }
  });
  try {
    escodegen.attachComments(ast, comments, tokens);
    walk.simple(ast, {
      Program(node) {
        for (let i = 0; i < node.body.length; i++) {
          if (
            node.body[i].type === 'ImportDeclaration' &&

acorn-jsx

Modern, fast React.js JSX parser

MIT
Latest version published 3 years ago

Package Health Score

74 / 100
Full package analysis

Similar packages