How to use magic-string - 10 common examples

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 esperantojs / esperanto / dist / esperanto.js View on Github external
function combine(bundle) {
	bundle.body = new MagicString.Bundle({
		separator: '\n\n'
	});

	// give each module in the bundle a unique name
	populateModuleNames(bundle);

	// determine which specifiers are imported from
	// external modules
	populateExternalModuleImports(bundle);

	// determine which identifiers need to be replaced
	// inside this bundle
	populateIdentifierReplacements(bundle);

	bundle.exports = resolveExports(bundle);
github magento / baler / src / createBundleFromDeps.ts View on Github external
function createBundle(
    modules: { dep: string; file: MagicString; hasInvalidShim: boolean }[],
) {
    const bundle = new Bundle();
    const depsWithInvalidShims: string[] = [];

    bundle.prepend(
        `/* Generated by @magento/baler - ${new Date().toISOString()} */\n\n`,
    );

    for (const { dep, file, hasInvalidShim } of modules) {
        bundle.addSource({
            filename: `../${dep}.js`,
            content: file,
        });
        if (hasInvalidShim) depsWithInvalidShims.push(dep);
    }

    return { bundle, depsWithInvalidShims };
}
github VadimDez / ngx-img-fallback / node_modules / angular-cli / node_modules / rollup / src / Bundle.js View on Github external
render ( options = {} ) {
		const format = options.format || 'es6';

		// Determine export mode - 'default', 'named', 'none'
		const exportMode = getExportMode( this, options.exports );

		let magicString = new MagicString.Bundle({ separator: '\n\n' });
		let usedModules = [];

		this.orderedModules.forEach( module => {
			const source = module.render( format === 'es6' );
			if ( source.toString().length ) {
				magicString.addSource( source );
				usedModules.push( module );
			}
		});

		const intro = [ options.intro ]
			.concat(
				this.plugins.map( plugin => plugin.intro && plugin.intro() )
			)
			.filter( Boolean )
			.join( '\n\n' );
github rollup / rollup / src / utils / collapseSourcemaps.ts View on Github external
// correct SourceMapSegment tuples. Cast it here to gain type safety.
	let source = new Link(map as ExistingDecodedSourceMap, moduleSources);

	source = bundleSourcemapChain.reduce(linkMap, source);

	let { sources, sourcesContent, names, mappings } = source.traceMappings();

	if (file) {
		const directory = dirname(file);
		sources = sources.map((source: string) => relative(directory, source));
		file = basename(file);
	}

	sourcesContent = (excludeContent ? null : sourcesContent) as string[];

	return new SourceMap({ file, sources, sourcesContent, names, mappings });
}
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);

magic-string

Modify strings, generate sourcemaps

MIT
Latest version published 9 days ago

Package Health Score

91 / 100
Full package analysis