How to use the loader-utils.interpolateName function in loader-utils

To help you get started, we’ve selected a few loader-utils 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 curioswitch / curiostack / common / web / base-web / src / dev / webpack / curio-image-loader / index.ts View on Github external
async function run(ctx: LoaderContext, content: Buffer) {
  ctx.async();
  ctx.cacheable(true);

  if (!ctx.resourceQuery) {
    // Passthrough when no options specified.
    const outputPath = interpolateName(ctx, '[name].[hash].[ext]', {
      content,
      context: ctx.context,
    });
    ctx.emitFile(outputPath, content, undefined);
    const publicPath = `__webpack_public_path__ + ${JSON.stringify(
      outputPath,
    )}`;
    ctx.callback(undefined, `export default ${publicPath}`);
    return;
  }

  const resourceOptions = parseQuery(ctx.resourceQuery) as ResourceOptions;

  const loaderOptions: LoaderOptions = {
    ...DEFAULT_OPTIONS,
    ...getOptions(ctx),
github SassNinja / media-query-plugin / src / plugin.js View on Github external
store.getMediaKeys().forEach(mediaKey => {

                    const css = store.getMedia(mediaKey);
                    const queries = store.getQueries(mediaKey);

                    // generate hash and use for [hash] within basename
                    const hash = interpolateName({}, `[hash:${compiler.options.output.hashDigestLength}]`, { content: css });

                    // compute basename according to filename option
                    // while considering hash
                    const basename = this.options.filename
                                        .replace('[name]', mediaKey)
                                        .replace(/\[(content|chunk)?hash\]/, hash)
                                        .replace(/\.[^.]+$/, '');

                    // if there's no chunk for the extracted media, create one 
                    if (chunkIds.indexOf(mediaKey) === -1) {
                        const mediaChunk = new Chunk(mediaKey);
                        mediaChunk.id = mediaKey;
                        mediaChunk.ids = [mediaKey];
                        chunks.push(mediaChunk);
                    }
github trustworktech / create-react-ssr-app / packages / react-ssr-dev-utils / getCSSModuleLocalIdent.js View on Github external
) {
  // Use the filename or folder name, based on some uses the index.js / index.module.(css|scss|sass) project style
  const fileNameOrFolder = context.resourcePath.match(
    /index\.module\.(css|scss|sass)$/
  )
    ? '[folder]'
    : '[name]';
  // Create a hash based on a the file location and class name. Will be unique across a project, and close to globally unique.
  const hash = loaderUtils.getHashDigest(
    context.resourcePath + localName,
    'md5',
    'base64',
    5
  );
  // Use loaderUtils to find the file or folder name
  const className = loaderUtils.interpolateName(
    context,
    fileNameOrFolder + '_' + localName + '__' + hash,
    options
  );
  // remove the .module that appears in every classname when based on the file.
  return className.replace('.module_', '_');
};
github itgalaxy / imagemin-webpack / src / ImageminPlugin.js View on Github external
const originalResourcePath = path.relative(
              context,
              result.filePath
            );

            // Exclude:
            // 1. Module assets (`file-loader` already interpolated asset name)
            // 2. Filtered assets
            if (moduleAssets.has(originalResourcePath) || result.filtered) {
              compilation.assets[originalResourcePath] = source;

              return;
            }

            const interpolatedName = loaderUtils.interpolateName(
              { resourcePath: path.join(context, originalResourcePath) },
              name,
              { content: source.source(), context }
            );

            compilation.assets[interpolatedName] = source;

            if (interpolatedName !== originalResourcePath) {
              delete compilation.assets[originalResourcePath];
            }

            if (manifest && !manifest[originalResourcePath]) {
              manifest[originalResourcePath] = interpolatedName;
            }
          });
github camptocamp / ngeo / buildtools / webpack.plugin.js View on Github external
parseOptions.functions['url($url)'] = function(url) {
        const assetUrl = url.getValue();
        if (assetUrl.startsWith('data:')) {
          return url;
        }
        return nodeSass.types.String(`url(${replacements[assetUrl]})`);
      };
      const result = nodeSass.renderSync(parseOptions);
      const content = doReplacement(result.css.toString(), pluginOptions.postReplacements);
      const srcmap = result.map;
      const asset = {
        source: () => content,
        size: () => content.length
      };
      usedContext.resourcePath = `/${chunk.name}`;
      const assetName = loaderUtils.interpolateName(usedContext, pluginOptions.filename, {
        content: content,
      });
      compilation.assets[assetName] = asset;
      chunk.files.push(assetName);
      if (srcmap) {
        compilation.assets[`${assetName}.map`] = {
          source: () => srcmap,
          size: () => srcmap.length
        };
        chunk.files.push(`${assetName}.map`);
      }
      usedContext.resourcePath = originalResourcePath;
      resolve();
    } catch (e) {
      console.error(e.stack || e);
      callback(`SCSS plugin error, ${e}`);
github developit / workerize-loader / src / index.js View on Github external
loader.pitch = function(request) {
	this.cacheable(false);

	const options = loaderUtils.getOptions(this) || {};

	const cb = this.async();

	const filename = loaderUtils.interpolateName(this, `${options.name || '[hash]'}.worker.js`, {
		context: options.context || this.rootContext || this.options.context,
		regExp: options.regExp
	});

	const worker = {};

	worker.options = {
		filename,
		chunkFilename: `[id].${filename}`,
		namedChunkFilename: null
	};

	const compilerOptions = this._compiler.options || {};
	if (compilerOptions.output && compilerOptions.output.globalObject==='window') {
		console.warn('Warning (workerize-loader): output.globalObject is set to "window". It should be set to "self" or "this" to support HMR in Workers.');
	}
github zeit / next.js / packages / next / build / webpack / loaders / emit-file-loader.js View on Github external
if (query.validateFileName) {
    try {
      query.validateFileName(resourcePath)
    } catch (err) {
      callback(err)
      return
    }
  }

  const name = query.name || '[hash].[ext]'
  const context = query.context || this.rootContext || this.options.context
  const regExp = query.regExp
  const opts = { context, content, regExp }
  const interpolateName = query.interpolateName || (name => name)
  const interpolatedName = interpolateName(
    loaderUtils.interpolateName(this, name, opts),
    { name, opts }
  )
  const emit = (code, map) => {
    this.emitFile(interpolatedName, code, map)
    callback(null, code, map)
  }

  if (query.transform) {
    const transformed = query.transform({
      content,
      sourceMap,
      interpolatedName,
    })
    return emit(transformed.content, transformed.sourceMap)
  }
github zendesk / app_scaffold / lib / loaders / translations-loader.js View on Github external
function TranslationsLoader(content) {
  this.cacheable && this.cacheable();
  var options = loaderUtils.getOptions(this);
  var name = options.name || "../translations/[name].json";
  var runtimePath = options.runtime || require.resolve("handlebars/runtime");

  var translationsInput = JSON.parse(content);
  var translationsPath = path.relative(this.options.context, this.resourcePath);
  var marketplaceTranslations = extractMarketplaceTranslation(
    translationsInput,
    translationsPath
  );
  var url = loaderUtils.interpolateName(this, name, {
    content: marketplaceTranslations
  });
  this.emitFile(url, marketplaceTranslations);

  var compiledTranslations = compileTranslations(translationsInput);
  return `
    var Handlebars = require(${JSON.stringify(runtimePath)});
    module.exports = ${compiledTranslations};
  `;
}
github WearyMonkey / ngtemplate-loader / index.js View on Github external
function getAndInterpolateOption(optionKey, def) {
        return options[optionKey]
            ? loaderUtils.interpolateName(this, options[optionKey], {
                context: options.context,
                content: content,
                regExp: options[optionKey + 'RegExp'] || options['regExp']
            })
            : def
    }
github sensu / sensu-go / dashboard / config / macroLoader.js View on Github external
emitFile(relativePath, fileContent, emitOptions) {
      const currentOptions = {
        filename: "[name].[ext]",
        ...options,
        ...emitOptions,
      };

      const resourcePath = path.join(
        path.dirname(context.resourcePath),
        relativePath,
      );

      const filename = loaderUtils.interpolateName(
        { ...context, resourcePath },
        currentOptions.filename,
        { content: fileContent },
      );

      context.emitFile(filename, fileContent);

      return `module.exports = __webpack_public_path__ + ${JSON.stringify(
        filename,
      )}`;
    },
  });