webpack#LoaderContext TypeScript Examples

The following examples show how to use webpack#LoaderContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: loader.ts    From reskript with MIT License 6 votes vote down vote up
export default async function playEntryLoader(this: LoaderContext<BuildEntryOptions>, content: any) {
    if (this.cacheable) {
        this.cacheable();
    }

    const callback = this.async();

    const options = this.getOptions();
    const source = await buildEntryScript(content.toString(), options);
    callback(null, source);
}
Example #2
Source File: index.ts    From reskript with MIT License 6 votes vote down vote up
export default async function svgToComponentLoader(this: LoaderContext<Options>, source: string) {
    this.cacheable();
    const callback = this.async();
    const {displayName = false} = this.getOptions();
    try {
        const code = await transformSvgToComponent(source, {displayName, resource: this.resourcePath});
        callback(null, code);
    }
    catch (ex) {
        const message = [
            `Failed to parse ${this.resourcePath}`,
            'please report to https://github.com/ecomfe/reskript/issues/new with svg\'s content',
        ];
        callback(new Error(message.join(', ')));
    }
}
Example #3
Source File: index.ts    From dts-loader with MIT License 6 votes vote down vote up
function makeLoader(
  context: LoaderContext<Partial<LoaderOptions>>,
  loaderOptions: LoaderOptions,
  content: string
) {
  const fileName = normalizePath(context.resourcePath)
  const hashedContent = hash(content);
  if (files[fileName] && files[fileName].hashedContent !== hashedContent) {
      // Update the content
      files[fileName].hashedContent = hashedContent;
      
      // Update the version to signal a change in the file
      files[fileName].version++;
  }
  
  const tsconfig = getTSConfig(context.rootContext)
  const languageService = getTSService({
    ...tsconfig,
    declaration: true,
    emitDeclarationOnly: true,
    outDir: path.resolve(
      context.rootContext,
      `${loaderOptions.typesOutputDir}/${loaderOptions.name}/dts`
    ),
  }, context.rootContext)

  emitFile(context, languageService, loaderOptions)

  return content
}
Example #4
Source File: index.ts    From dts-loader with MIT License 6 votes vote down vote up
export default function loader(content: string) {
  // @ts-ignore
  const context: LoaderContext<Partial<LoaderOptions>> = this
  const loaderOptions = context.getOptions()

  return makeLoader(
    context,
    {
      name: loaderOptions.name,
      exposes: loaderOptions.exposes,
      typesOutputDir: loaderOptions.typesOutputDir || '.wp_federation',
    },
    content
  )
}
Example #5
Source File: index.ts    From swc-node with MIT License 6 votes vote down vote up
export function loader(
  this: LoaderContext<{
    compilerOptions?: CompilerOptions
    configFile?: string
    fastRefresh?: boolean
  }>,
  source: string,
) {
  const callback = this.async()
  const { compilerOptions, configFile, fastRefresh } = this.getOptions() ?? {}
  const options = convertCompilerOptionsFromJson(compilerOptions, '').options ?? readDefaultTsConfig(configFile)
  const swcOptions = tsCompilerOptionsToSwcConfig(options, this.resourcePath)
  if (fastRefresh) {
    if (swcOptions.react) {
      swcOptions.react.refresh = true
    } else {
      swcOptions.react = {
        refresh: true,
      }
    }
  }
  transform(source, this.resourcePath, swcOptions)
    .then(({ code, map }) => callback(null, code, map))
    .catch((err) => callback(err))
}
Example #6
Source File: index.ts    From tailchat with GNU General Public License v3.0 5 votes vote down vote up
async function loader(this: LoaderContext<any>, source: string): Promise<void> {
  const done = this.async();

  const { available } = this.getOptions();
  if (!available) {
    // skip if not
    done(null, source);
    return;
  }

  const ast = parse(source, {
    sourceType: 'module',
    plugins: ['jsx', 'typescript'],
  });
  const filepath = this.resourcePath;
  if (filepath.includes('node_modules')) {
    done(null, source);
    return;
  }

  traverse(ast, {
    JSXOpeningElement(path) {
      const location = path.node.loc;
      if (!location) {
        return;
      }

      if (Array.isArray(location)) {
        return;
      }

      const name = path.node.name;
      if (isJSXIdentifier(name) && name.name === 'Fragment') {
        return;
      }
      if (isJSXMemberExpression(name) && name.property.name === 'Fragment') {
        return;
      }

      const line = location.start.line;
      const col = location.start.column;

      const attrs = path.node.attributes;
      for (let i = 0; i < attrs.length; i++) {
        const attr = attrs[i];
        if (attr.type === 'JSXAttribute' && attr.name.name === TRACE_ID) {
          // existed
          return;
        }
      }

      const traceId = `${filepath}:${line}:${col}`;

      attrs.push(jsxAttribute(jsxIdentifier(TRACE_ID), stringLiteral(traceId)));
    },
  });

  const code = generate(ast).code;

  done(null, code);
}
Example #7
Source File: index.ts    From dts-loader with MIT License 5 votes vote down vote up
function emitFile(
  context: LoaderContext<Partial<LoaderOptions>>,
  languageService: ts.LanguageService,
  loaderOptions: LoaderOptions,
) {
  const fileName = context.resourcePath
  try {
    const output = languageService.getEmitOutput(fileName)
    if (!output.emitSkipped) {
      output.outputFiles.forEach((o) => {
        if (o.name.endsWith('.d.ts')) {
          fs.ensureDirSync(path.dirname(o.name))
          fs.writeFileSync(o.name, o.text)

          if (
            loaderOptions.exposes &&
            !isEmpty(loaderOptions.exposes) &&
            !isEmpty(loaderOptions.name)
          ) {
            for (const [key, value] of Object.entries(loaderOptions.exposes)) {
              if (key && value) {
                context.resolve(context.rootContext, value, (err, inputFilePath) => {
                  if (err) {
                    console.error(err)
                    return
                  }
                  if (inputFilePath === fileName) {
                    const moduleFilename = `${key}.d.ts`
                    const modulePath = path.resolve(
                      context.rootContext,
                      `${loaderOptions.typesOutputDir}/${loaderOptions.name}`
                    )
                    const dtsEntryPath = path.resolve(modulePath, moduleFilename)
                    const relativePathToOutput = normalizePath(
                      path.relative(
                        path.dirname(dtsEntryPath),
                        o.name.replace('.d.ts', '')
                      )
                    )

                    fs.ensureFileSync(dtsEntryPath)
                    fs.writeFileSync(
                      dtsEntryPath,
                      `export * from './${relativePathToOutput}';\nexport { default } from './${relativePathToOutput}';`
                    )
                  }
                })
              }
            }
          }
        }
      })
    }
  } catch (e) {
    console.log(`Skip ${fileName}`)
  }
}