How to use the magic-string function in magic-string

To help you get started, we’ve selected a few magic-string 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 esperantojs / esperanto / src / standalone / getModule.js View on Github external
export default function getStandaloneModule ( options ) {
	let code, ast;

	if ( typeof options.source === 'object' ) {
		code = options.source.code;
		ast = options.source.ast;
	} else {
		code = options.source;
	}

	let toRemove = [];

	let mod = {
		body: new MagicString( code ),
		ast: ast || ( acorn.parse( code, {
			ecmaVersion: 6,
			sourceType: 'module',
			onComment ( block, text, start, end ) {
				// sourceMappingURL comments should be removed
				if ( !block && SOURCEMAPPINGURL_REGEX.test( text ) ) {
					toRemove.push({ start, end });
				}
			}
		}))
	};

	toRemove.forEach( ({ start, end }) => mod.body.remove( start, end ) );

	let { imports, exports, defaultExport } = findImportsAndExports( mod.ast, code );
github ampproject / rollup-plugin-closure-compiler / src / transformers / exports.ts View on Github external
public async preCompilation(code: string): Promise {
    if (isESMFormat(this.outputOptions.format)) {
      await this.deriveExports(code);
      const source = new MagicString(code);

      for (const key of this.originalExports.keys()) {
        const value: ExportDetails = this.originalExports.get(key) as ExportDetails;

        // Remove export statements before Closure Compiler sees the code
        // This prevents CC from transpiling `export` statements when the language_out is set to a value
        // where exports were not part of the language.
        source.remove(...value.range);
        // Window scoped references for each key are required to ensure Closure Compilre retains the code.
        if (value.source === null) {
          source.append(`\nwindow['${value.closureName}'] = ${value.local};`);
        } else {
          source.append(`\nwindow['${value.closureName}'] = ${value.exported};`);
        }
      }
github aMarCruz / rollup-plugin-jscc / src / jscc / preproc.js View on Github external
export default function preproc (code, filename, _options) {

  const options   = parseOptions(filename, _options)
  const magicStr  = new MagicString(code)
  const parser    = new Parser(options)

  const re = parser.getRegex()  // $1:keyword, $2:expression

  let changes   = false
  let output    = true
  let hideStart = 0
  let lastIndex
  let match

  re.lastIndex = lastIndex = 0

  while ((match = re.exec(code))) {
    let index = match.index

    if (output) {
github rollup / rollup / src / Module.ts View on Github external
}

		timeStart('generate ast', 3);

		this.esTreeAst = ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions);
		markPureCallExpressions(this.comments, this.esTreeAst);

		timeEnd('generate ast', 3);

		this.resolvedIds = resolvedIds || Object.create(null);

		// By default, `id` is the file name. Custom resolvers and loaders
		// can change that, but it makes sense to use it for the source file name
		const fileName = this.id;

		this.magicString = new MagicString(code, {
			filename: (this.excludeFromSourcemap ? null : fileName) as string, // don't include plugin helpers in sourcemap
			indentExclusionRanges: []
		});
		this.removeExistingSourceMap();

		timeStart('analyse ast', 3);

		this.astContext = {
			addDynamicImport: this.addDynamicImport.bind(this),
			addExport: this.addExport.bind(this),
			addImport: this.addImport.bind(this),
			addImportMeta: this.addImportMeta.bind(this),
			annotations: (this.graph.treeshakingOptions &&
				this.graph.treeshakingOptions.annotations) as boolean,
			code, // Only needed for debugging
			deoptimizationTracker: this.graph.deoptimizationTracker,
github remaxjs / remax / packages / remax-cli / src / build / plugins / removeSrc.ts View on Github external
files.map(file => {
        if (PREFIX_SRC_PATTERN.test(file)) {
          const module = bundle[file];
          if (isAsset(module)) {
            return;
          }

          module.fileName = rewrite(module.fileName);
          module.facadeModuleId = rewrite(module.fileName);

          if (module.code) {
            const magicString = new MagicString(module.code);
            const ast = this.parse(module.code, {
              sourceType: 'module',
            });

            const extract = (node: Node) => {
              const req =
                getRequireSource(node) ||
                getImportSource(node) ||
                getExportSource(node);
              if (req) {
                const { start, end } = req;
                const distance = req.value
                  .split('/')
                  .filter((d: string) => d === '..').length;
                const targetDistance = winPath(
                  path.relative(path.dirname(file), options.rootDir)
github rollup / plugins / packages / strip / src / index.js View on Github external
transform(code, id) {
      if (!filter(id)) return null;
      if (functions.length > 0 && !firstpass.test(code)) return null;

      let ast;

      try {
        ast = this.parse(code);
      } catch (err) {
        err.message += ` in ${id}`;
        throw err;
      }

      const magicString = new MagicString(code);
      let edited = false;

      function remove(start, end) {
        while (whitespace.test(code[start - 1])) start -= 1;
        magicString.remove(start, end);
      }

      function isBlock(node) {
        return node && (node.type === 'BlockStatement' || node.type === 'Program');
      }

      function removeExpression(node) {
        const { parent } = node;

        if (parent.type === 'ExpressionStatement') {
          removeStatement(parent);
github luwes / rollup-plugin-tagged-template / src / tagged-template.js View on Github external
function template(code, { tagName, propsName }) {
  const defs = getIdentifiers(code).map(exp => `${exp} = ${propsName}.${exp}`);
  const statement = defs.length ? `var ${defs.join(', ')};` : '';

  return new MagicString(`
export default function template(${tagName}, ${propsName}) {
  ${propsName} = ${propsName} || {};
  ${statement}
  return ${tagName}\`${code}\`;
}`);
}
github developit / rollup-plugin-preserve-shebang / index.js View on Github external
transformBundle(code, { format, sourcemap }) {
			if (!shebang) return;

			let str = new MagicString(code);
			str.prepend(shebang+'\n');
			return {
				code: str.toString(),
				map: sourcemap ? str.generateMap({ hires: true }) : undefined
			};
		}
	};
github decaffeinate / decaffeinate / src / stages / TransformCoffeeScriptStage.ts View on Github external
static run(content: string, options: Options): StageResult {
    const log = logger(this.name);
    log(content);

    const context = DecaffeinateContext.create(content, Boolean(options.useCS2));
    const editor = new MagicString(content);
    const stage = new this(context.programNode, context, editor, options);
    const patcher = stage.build();
    patcher.patch();
    return {
      code: editor.toString(),
      suggestions: stage.suggestions
    };
  }

magic-string

Modify strings, generate sourcemaps

MIT
Latest version published 20 days ago

Package Health Score

89 / 100
Full package analysis