How to use babel-generator - 10 common examples

To help you get started, we’ve selected a few babel-generator 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 salesforce / design-system-react / scripts / code / find-and-fix-missing-doc-stories.js View on Github external
try {
		siteStories(cmp); // Checks for existence of this
		const cmpStoriesAST = astFromBuffer(componentStories(cmp));
		const imports = importsFromAST(cmpStoriesAST).filter(isExampleImport);

		const isExampleImported = (ex) =>
			imports.some((i) => ex.includes(path.basename(i.source.value)));

		const examples = componentExamples(cmp);
		const isValid = examples.every(isExampleImported);
		if (!isValid) {
			const missing = examples.filter((e) => !isExampleImported(e));
			// babel-traverse walks the AST and modifies it
			babel.traverse(cmpStoriesAST, createAddDocsImportVisitor(missing));
			// babel-generator converts AST into source code
			const newBody = generator.default(cmpStoriesAST).code; // Note, this doesn't have good formatting, run prettier on the files afterward
			// eslint-disable-next-line no-console
			console.log(
				`${cmp} will get the following files added: \n\t${missing.join(
					',\n\t'
				)}`
			);
			fs.writeFileSync(storiesFor(cmp), newBody);
		}
	} catch (error) {
		if (
			error.code === 'ENOENT' &&
			error.path &&
			error.path.match(/storybook-stories/)
		) {
			// console.log(`No stories for: ${cmp}`);
		} else if (
github awto / effectfuljs / src / trace.js View on Github external
export function cg(ast, opts = {}) {
  var res
  if (ast == null) {
    // console.error("")
    return ""
  }
  try {
    if (Array.isArray(ast)) {
      ast = ast.length > 0 && T.isExpression(ast[0]) 
        ? T.sequenceExpression(ast)
        : T.blockStatement(ast)
    }
    res = generate(ast,opts,"").code
  } catch (e) {
    if (ast.type != null)
      console.error(e.stack)
  }
  if (res != null)
    return res
  try {
    return "!!" + opts.compact ? JSON.stringify(ast) : JSON.stringify(ast,null,2)
  } catch(e) {
    return ""
  }
}
github trivago / melody / packages / melody-compiler / src / index.js View on Github external
export function toString(jsAst, code) {
    const g = new CodeGenerator(jsAst, {}, code);
    // Babel sanitises strings to not contain complex characters
    // however we need them in order to be able to render complex strings
    g._generator.StringLiteral = function(node, parent) {
        var raw = this.getPossibleRaw(node);
        if (!this.format.minified && raw != null) {
            this.token(raw);
            return;
        }

        return this.token(JSON.stringify(node.value));
    };
    return g.generate();
}
github drd / jsxlate / bin / bundle-messages.js View on Github external
files.forEach(function (filename) {
    var buffer = fs.readFileSync(filename, "utf8");
    try {
        var translationsForFile = translateMessagesToBundle(buffer, translations, { inputFormat: format });
    } catch (e) {
        console.error(chalk.bold.red("\nError in file " + filename + ":"));
        console.error(e);
        console.error(e.stack);
        e.node && console.error(generate(e.node));
        process.exit(1);
    }
    Object.keys(translationsForFile.bundle).forEach(function (message) {
        bundle[message] = translationsForFile.bundle[message];
    });
    Object.keys(translationsForFile.missing).forEach(function (message) {
        missing[message] = message;
    });
});
github node-cube / cube / lib / cube / ext_api_process.js View on Github external
if (typeof ast === 'string') {
      opt.code = ast;
    } else {
      /*
       目前babel 6 版本的 遍历功能看起来对ast有污染,无法做到ast复用去minify
       所以需要fix一次ast
       */
      opt.ast = fixAst(ast);
    }
    opt.config = minifyOpt;
    return esminify.minify(opt);
  } else {
    if (typeof ast === 'string') {
      return ast;
    }
    let out = babelGenerator(ast, {
      retainLines: true,
      filename: qpath,
      quotes: 'single'
    });
    return out.code;
  }
}
github FE-Kits / Ueact / packages / ueact-tiga / packages / taro-cli / src / h5.js View on Github external
t.identifier(renameComponentClassName),
                node.superClass,
                node.body,
                node.decorators || []
              )
            );
            componentClassName = renameComponentClassName;
          } else {
            componentClassName = node.id.name;
          }
        }
      }
    }
  });
  return {
    code: generate(ast).code,
    taroImportDefaultName,
    componentClassName,
    styleFiles
  };
}
github alibaba / ice / tools / iceworks / app / main / scaffolder / lib / appendMenuV4.js View on Github external
if (op.key.name === 'path' && op.value.value === path) {
              return true;
            }
            return false;
          });
        });
        if (!menuExist) {
          node.init.elements.push(menuNode({ name, path, icon }));
        }
      }
    },
  });

  fs.writeFileSync(
    menuConfigFilePath,
    prettier.format(generator(menuConfigAST).code, config.prettier)
  );
};
github rekit / rekit / packages / rekit-core / core / refactor / importExport.js View on Github external
const specifiers = [];
    if (defaultImport) {
      specifiers.push(t.importDefaultSpecifier(t.identifier(defaultImport)));
    }
    if (namespaceImport) {
      specifiers.push(t.importNamespaceSpecifier(t.identifier(namespaceImport)));
    }

    names.forEach((n) => {
      const local = t.identifier(n);
      const imported = local;
      specifiers.push(t.importSpecifier(local, imported));
    });

    const node = t.importDeclaration(specifiers, t.stringLiteral(moduleSource));
    const code = generate(node, babelGeneratorOptions).code;
    changes.push({
      start: targetImportPos,
      end: targetImportPos,
      replacement: `${code}\n`,
    });
  }

  return changes;
}
github makuga01 / dnsFookup / FE / node_modules / cssstyle / scripts / generate_properties.js View on Github external
[t.identifier('prototype'), t.objectExpression(propertyDefinitions)]
);
statements.push(
  t.expressionStatement(
    t.assignmentExpression(
      '=',
      t.memberExpression(t.identifier('module'), t.identifier('exports')),
      t.functionExpression(
        null,
        [t.identifier('prototype')],
        t.blockStatement([t.expressionStatement(definePropertiesCall)])
      )
    )
  )
);
out_file.write(generate(t.program(statements)).code + '\n');
out_file.end(function(err) {
  if (err) {
    throw err;
  }
});
github Tencent / omi / packages / cax-omip / scripts / taro-cli / src / weapp.js View on Github external
node.body[index] = null
                }
              }
            })

            //@fix 注释掉用来解决小程序报错
            //node.body.push(template(`Component(require('${taroMiniAppFrameworkPath}').default.createComponent(${exportVariableName}))`, babylonConfig)())
            break
          default:
            break
        }
      }
    }
  })
  return {
    code: generate(ast).code,
    styleFiles,
    scriptFiles,
    jsonFiles,
    configObj,
    mediaFiles,
    componentClassName
  }
}

babel-generator

Turns an AST into code.

MIT
Latest version published 7 years ago

Package Health Score

88 / 100
Full package analysis

Similar packages