How to use acorn-jsx - 10 common examples

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 hitext / hitext / src / temp-generators / lang-js / syntax.js View on Github external
case acorn.tokTypes.bitwiseOR:
                    case acorn.tokTypes.bitwiseXOR:
                    case acorn.tokTypes.bitwiseAND:
                    case acorn.tokTypes.equality:
                    case acorn.tokTypes.relational:
                    case acorn.tokTypes.bitShift:
                    case acorn.tokTypes.plusMin:
                    case acorn.tokTypes.modulo:
                    case acorn.tokTypes.star:
                    case acorn.tokTypes.slash:
                    case acorn.tokTypes.starstar:
                        type = 'operator';
                        break;

                    case acorn.keywordTypes.true:
                    case acorn.keywordTypes.false:
                    case acorn.keywordTypes.null:
                    case acorn.keywordTypes.undefined:
                        type = 'value-keyword';
                        break;

                    default:
                        if (token.type.keyword) {
                            type = 'keyword';
                            break;
                        }

                        // console.log('Unknown type', token);
                }
        }

        if (type) {
github fourcube / unused / src / lib.js View on Github external
fs.readFile(path, {encoding: 'utf-8'}, function(err, data) {
    if(err) {
      return cb(err, null);
    }
    // first apply a jsx transformation
    data = jsx.transform(data, {
      harmony: true,
      es6module: true
    });

    cb(null, acorn.parse(data, {
      sourceType: 'module',
      ecmaVersion: "6",
      locations: true,
      plugins: {
        'jsx': true
      }
    }));
  });
}
github zaach / jsxgettext / lib / jsxgettext.js View on Github external
sourceType: 'module',
      plugins: { jsx: { allowNamespaces: false } },
      onComment: function (block, text, start, end, line/*, column*/) {
        text = text.match(commentRegex) && text.replace(/^\//, '').trim();

        if (!text)
          return;

        astComments.push({
          line : line,
          value: text
        });
      },
      locations: true
    }, options.parserOptions && JSON.parse(options.parserOptions));
    var ast      = parser.parse(source, parserOptions);

    // finds comments that end on the previous line
    function findComments(comments, line) {
      return comments.map(function (node) {
        var commentLine = node.line.line;
        if (commentLine === line || commentLine + 1 === line) {
          return node.value;
        }
      }).filter(Boolean).join('\n');
    }

     walk.simple(ast, {'CallExpression': function (node) {
        var arg = getTranslatable(node, options);
        if (!arg)
          return;
github fourcube / unused / lib / lib.js View on Github external
fs.readFile(path, { encoding: 'utf-8' }, function (err, data) {
    if (err) {
      return cb(err, null);
    }
    // first apply a jsx transformation
    data = jsx.transform(data, {
      harmony: true,
      es6module: true
    });

    cb(null, acorn.parse(data, {
      sourceType: 'module',
      ecmaVersion: '6',
      locations: true,
      plugins: {
        'jsx': true
      }
    }));
  });
}
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');
      }
    },

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