webpack#Compiler TypeScript Examples

The following examples show how to use webpack#Compiler. 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: index.ts    From react-typescript-boilerplate with MIT License 6 votes vote down vote up
/**
 * 配置中间件
 */
export default function setupMiddlewares(server: Express, compiler: Compiler): void {
    // 设置代理
    proxyMiddleware(server);

    // 使用 browserRouter 时,需要重定向所有 html 页面到首页
    server.use(historyFallback());

    // 开发 chrome 扩展的时候可能需要开启跨域,参考:https://juejin.im/post/5e2027096fb9a02fe971f6b8
    server.use(cors());

    // webpack 相关中间件
    server.use(webpackMiddleware(compiler));
}
Example #2
Source File: inspector-plugin.ts    From react-dev-inspector with MIT License 6 votes vote down vote up
public apply(compiler: Compiler) {
    if (!compiler.options.devServer) {
      compiler.options.devServer = {}
    }
    const { devServer } = compiler.options

    /**
     * for webpack@^5 + webpack-dev-server@^4.7
     */
    const originSetup = devServer.setupMiddlewares
    devServer.setupMiddlewares = (middlewares, devServer) => {
      const result = originSetup ? originSetup(middlewares, devServer) : middlewares
      result.unshift(launchEditorMiddleware)
      return result
    }

    /**
     * for webpack@^4 + webpack-dev-server@^3
     */
    const originBefore = devServer.before
    devServer.before = (app, server, compiler) => {
      app.use(launchEditorMiddleware)
      originBefore?.(app, server, compiler)
    }
  }
Example #3
Source File: mini-program-application-analysis.service.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
constructor(
    private injector: Injector,
    @Inject(WEBPACK_COMPILATION) private compilation: Compilation,
    @Inject(TS_SYSTEM) private system: ts.System,
    @Inject(WEBPACK_COMPILER) private compiler: Compiler,
    @Inject(TS_CONFIG_TOKEN) private tsConfig: string,
    @Inject(OLD_BUILDER)
    private oldBuilder: ts.EmitAndSemanticDiagnosticsBuilderProgram | undefined,
    @Inject(PAGE_PATTERN_TOKEN) private pagePatternList: PagePattern[],
    private buildPlatform: BuildPlatform
  ) {}
Example #4
Source File: webpack.ts    From mpflow with MIT License 6 votes vote down vote up
export function readAssets(compiler: Compiler, stats: Stats): Record<string, string> {
  const assets: Record<string, string> = {}

  Object.keys(stats.compilation.assets).forEach(asset => {
    assets[asset] = readAsset(asset, compiler, stats)
  })

  return assets
}
Example #5
Source File: webpack.ts    From mpflow with MIT License 6 votes vote down vote up
export function readAsset(asset: string, compiler: Compiler, stats: Stats): string {
  const outFs = (compiler.outputFileSystem as any) as IFs
  const outputPath: string = stats.compilation.outputOptions.path

  let data = ''
  let targetFile = asset

  const queryStringIdx = targetFile.indexOf('?')

  if (queryStringIdx >= 0) {
    targetFile = targetFile.substr(0, queryStringIdx)
  }

  try {
    data = outFs.readFileSync(path.join(outputPath, targetFile)).toString()
  } catch (error) {
    data = error.toString()
  }

  return data
}
Example #6
Source File: webpack.ts    From mpflow with MIT License 6 votes vote down vote up
export function getCompiler(config: Configuration): Compiler {
  const fullConfig = merge(
    {
      mode: 'development',
      devtool: false,
      target: 'node',
      optimization: {
        minimize: false,
        namedModules: false,
      },
      output: {
        filename: '[name].bundle.js',
        chunkFilename: '[name].chunk.js',
        libraryTarget: 'commonjs2',
        pathinfo: false,
      },
    },
    config,
  )

  const compiler = webpack(fullConfig)

  const outputFileSystem = createFsFromVolume(new Volume())

  compiler.outputFileSystem = Object.assign(outputFileSystem, { join: path.join.bind(path) })

  return compiler
}
Example #7
Source File: pretty.ts    From mpflow with MIT License 6 votes vote down vote up
apply(compiler: Compiler) {
    compiler.hooks.done.tap(pluginName, stats => {
      if (stats.hasErrors()) {
        console.error(stats.toString('errors-only'))
        return
      }

      if (stats.hasWarnings()) {
        console.warn(stats.toString('errors-warnings'))
      }

      const { assetsByChunkName } = stats.toJson({
        all: false,
        modules: true,
        assets: true,
      })

      const assets = Object.keys(assetsByChunkName || {}).filter(key => !key.startsWith('common~') && key !== 'runtime')

      const time = new Date().toLocaleTimeString()
      const log = (...args: string[]) => console.log(chalk.green(`[${time}]`), ...args)

      if (stats.endTime && stats.startTime) {
        const duration = stats.endTime - stats.startTime
        log('⏱️ ', chalk.green(`Built in ${duration}ms`))
      }
      assets.forEach(name => {
        log('?', chalk.blue(name))
      })
      log('?', chalk.magenta(`Webpack compile finished!`))
    })
  }
Example #8
Source File: webpackMiddleware.ts    From react-typescript-boilerplate with MIT License 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export default function webpackMiddleware(compiler: Compiler) {
    const publicPath = devConfig.output!.publicPath!;

    const devMiddlewareOptions: webpackDevMiddleware.Options = {
        // 保持和 webpack 中配置一致
        publicPath,
        // 只在发生错误或有新的编译时输出
        stats: 'minimal',
        // 需要输出文件到磁盘可以开启
        // writeToDisk: true
    };

    const hotMiddlewareOptions: webpackHotMiddleware.MiddlewareOptions = {
        // sse 路由
        path: HMR_PATH,
    };

    return [
        webpackDevMiddleware(compiler, devMiddlewareOptions),
        webpackHotMiddleware(compiler, hotMiddlewareOptions),
    ];
}
Example #9
Source File: index.ts    From apl-viewhost-web with Apache License 2.0 6 votes vote down vote up
apply(compiler: Compiler) {
        this.compiler = compiler;
        compiler.plugin('done', () => {
            const name = path.basename(compiler.context);
            const m = new NodeModules(this.options.require, compiler.outputPath);
            m.addModule(name, true);
            m.transformAll();
        });
    }
Example #10
Source File: index.ts    From vanilla-extract with MIT License 6 votes vote down vote up
function markCSSFilesAsSideEffects(compiler: Compiler, compat: WebpackCompat) {
  compiler.hooks.normalModuleFactory.tap(pluginName, (nmf) => {
    if (compat.isWebpack5) {
      nmf.hooks.createModule.tap(
        pluginName,
        // @ts-expect-error CreateData is typed as 'object'...
        (createData: {
          matchResource?: string;
          settings: { sideEffects?: boolean };
        }) => {
          if (
            createData.matchResource &&
            createData.matchResource.endsWith('.vanilla.css')
          ) {
            createData.settings.sideEffects = true;
          }
        },
      );
    } else {
      nmf.hooks.afterResolve.tap(
        pluginName,
        // @ts-expect-error Can't be typesafe for webpack 4
        (result: {
          matchResource?: string;
          settings: { sideEffects?: boolean };
        }) => {
          if (
            result.matchResource &&
            result.matchResource.endsWith('.vanilla.css')
          ) {
            result.settings.sideEffects = true;
          }
        },
      );
    }
  });
}
Example #11
Source File: index.ts    From vanilla-extract with MIT License 6 votes vote down vote up
apply(compiler: Compiler) {
    const compat = createCompat(
      Boolean(compiler.webpack && compiler.webpack.version),
    );

    markCSSFilesAsSideEffects(compiler, compat);

    compiler.options.module?.rules.splice(0, 0, {
      test: this.test,
      use: [
        {
          loader: require.resolve('../loader'),
          options: {
            outputCss: this.outputCss,
            childCompiler: this.childCompiler,
            identifiers: this.identifiers,
          },
        },
      ],
    });
  }
Example #12
Source File: index.ts    From webpack-remote-types-plugin with MIT License 6 votes vote down vote up
apply(compiler: Compiler) {
    const tapCallback = async () => {
      const { remotes, remoteFileName, outputDir } = this.options
      const output = path.resolve(cwd, outputDir)
      const paramsChanged = this.remotes !== remotes || this.outputDir !== output || this.remoteFileName !== remoteFileName
      if (paramsChanged) {
        await downloadFederationTypes(remotes, output, remoteFileName)
        this.remotes = remotes
        this.outputDir = output
        this.remoteFileName = remoteFileName
      }
    }

    compiler.hooks.beforeRun.tapPromise('WebpackRemoteTypesPlugin', tapCallback)
    compiler.hooks.watchRun.tapPromise('WebpackRemoteTypesPlugin', tapCallback)
  }
Example #13
Source File: addWebpackPlugin.ts    From nextclade with MIT License 6 votes vote down vote up
export function addWebpackPlugin(
  nextConfig: NextConfig,
  plugin: WebpackPluginInstance | WebpackPluginFunction | ((this: Compiler, compiler: Compiler) => void) | any,
) {
  return addWebpackConfig(
    nextConfig,
    (nextConfig: NextConfig, webpackConfig: Configuration, { isServer }: WebpackConfigContext) => {
      if (!isServer) {
        if (webpackConfig?.plugins) {
          webpackConfig.plugins.push(plugin)
        } else {
          return { plugins: [plugin] }
        }
      }
      return webpackConfig
    },
  )
}
Example #14
Source File: webpack.ts    From mordred with MIT License 6 votes vote down vote up
apply(compiler: Compiler) {
    if (initialized) {
      return
    }

    initialized = true

    const webpackContext = compiler.context || process.cwd()

    const config = this.loadConfig(webpackContext)

    const mordred = new Mordred(config, {
      cwd: webpackContext,
    })

    let started = false
    compiler.hooks.watchRun.tapPromise('mordred', async () => {
      if (started) {
        return
      }
      started = true
      await mordred.init()
    })
    compiler.hooks.run.tapPromise('mordred', async () => {
      await mordred.init()
    })
  }
Example #15
Source File: ProgressBarPlugin.ts    From reskript with MIT License 6 votes vote down vote up
apply(compiler: Compiler) {
        this.handler = (percentage: number, stage, message) => {
            this.lastPercentage = percentage;
            if (this.working) {
                this.progressBar.update(Math.max(percentage, this.lastPercentage), {stage, message});
            }
        };
        compiler.hooks.beforeCompile.tap(
            'progress-bar-plugin',
            () => {
                this.working = true;
                this.progressBar.start(1, 0);
            }
        );
        compiler.hooks.afterEmit.tap(
            'progress-bar-plugin',
            () => {
                this.progressBar.update(1);
                this.progressBar.stop();
                this.working = false;
            }
        );
        process.on('SIGINT', () => (this.working = false));
        super.apply(compiler);
    }
Example #16
Source File: utils.ts    From react-loosely-lazy with Apache License 2.0 6 votes vote down vote up
buildManifest = (
  compiler: Compiler,
  compilation: Compilation,
  config: {
    moduleImports: Map<string, Set<string>>;
    publicPath: string | undefined;
  }
): Manifest => {
  const { context } = compiler.options;
  const { chunkGroups, outputOptions } = compilation;

  const publicPath = config.publicPath ?? outputOptions.publicPath;

  return (chunkGroups as ChunkGroup[]).reduce<Manifest>(
    (manifest, group) => {
      const { chunks, origins } = group;
      for (const origin of origins) {
        const { module: originModule, request } = origin;
        if (!originModule) {
          continue;
        }

        const { resource } = originModule;
        const rawRequests = config.moduleImports.get(resource) || new Set();
        if (!rawRequests.has(request)) {
          continue;
        }

        const block = originModule.blocks.find(
          b => b.request === request && b.module === originModule
        );

        if (!block) {
          continue;
        }

        const dependency = block.dependencies.find(
          (dep: any) =>
            dep.request === request && dep.originModule === originModule
        );

        if (!dependency) {
          continue;
        }

        const { module } = dependency;
        if (!module || !module.libIdent) {
          continue;
        }

        const name = module.libIdent({ context });
        if (!name || manifest.assets[name]) {
          continue;
        }

        for (const chunk of chunks) {
          if (chunk.isOnlyInitial()) {
            continue;
          }

          for (const file of chunk.files) {
            if (file.endsWith('.map')) {
              continue;
            }

            if (!manifest.assets[name]) {
              manifest.assets[name] = [];
            }

            manifest.assets[name].push(file);
          }
        }
      }

      return manifest;
    },
    { publicPath, assets: {} }
  );
}
Example #17
Source File: index.ts    From reskript with MIT License 5 votes vote down vote up
apply(compiler: Compiler) {
        compiler.hooks.compilation.tap('interpolate-html-webpack-plugin', compilation => this.replace(compilation));
    }
Example #18
Source File: webpack.ts    From mpflow with MIT License 5 votes vote down vote up
export function compile(compiler: Compiler): Promise<Stats> {
  return new Promise((resolve, reject) => {
    compiler.run((error, stats) => (error ? reject(error) : resolve(stats)))
  })
}
Example #19
Source File: plugin.ts    From reskript with MIT License 5 votes vote down vote up
apply(compiler: Compiler) {
        compiler.hooks.compilation.tap('transform-html-webpack-plugin', compilation => this.inject(compilation));
    }
Example #20
Source File: webpack.ts    From mpflow with MIT License 5 votes vote down vote up
export function getExecutedCode<T = any>(asset: string, compiler: Compiler, stats: Stats): T {
  return execute<T>(readAsset(asset, compiler, stats))
}
Example #21
Source File: index.d.ts    From mpflow with MIT License 5 votes vote down vote up
apply(compiler: Compiler): void
Example #22
Source File: index.d.ts    From mpflow with MIT License 5 votes vote down vote up
static target: (compiler: Compiler) => void
Example #23
Source File: index.ts    From apl-viewhost-web with Apache License 2.0 5 votes vote down vote up
private compiler: Compiler;
Example #24
Source File: index.ts    From react-loosely-lazy with Apache License 2.0 4 votes vote down vote up
apply(compiler: Compiler) {
    const { name, publicPath } = this;
    // A mapping of module paths to the set of raw requests that stem from the react-loosely-lazy library
    const moduleImports = new Map<string, Set<string>>();

    const onJavaScriptModule = (parser: Parser) => {
      let currentLibraryExpression: undefined | any;
      let hasLibraryImport = false;

      parser.hooks.import.tap(name, (statement: any, source: string) => {
        if (source === PACKAGE_NAME) {
          hasLibraryImport = true;
        }
      });

      parser.hooks.evaluate
        .for('CallExpression')
        .tap(name, (expression: any) => {
          // Perform an earlier bailout than checking the harmony specifiers
          if (!hasLibraryImport) {
            return;
          }

          const calleeName = expression.callee.name;
          // @ts-expect-error Parser types are not defined correctly
          const { harmonySpecifier } = parser.state;
          // TODO Someday handle proxies, and defined webpack aliases
          if (
            harmonySpecifier &&
            harmonySpecifier.has(calleeName) &&
            harmonySpecifier.get(calleeName).source === PACKAGE_NAME
          ) {
            currentLibraryExpression = expression;
          }
        });

      // This is a slightly hacky, but convenient way to get the import statement of a library expression as it does not
      // require walking the call expression ourselves.
      parser.hooks.importCall.tap(name, (expression: any) => {
        // If a library expression is present, then that means this import call exists within the library expression
        // assuming that the parser always traverses in a depth-first fashion
        if (currentLibraryExpression) {
          const rawRequest = expression.arguments[0].value;
          // @ts-expect-error Parser types are not defined correctly
          const { module } = parser.state;
          if (!moduleImports.has(module.resource)) {
            moduleImports.set(module.resource, new Set([rawRequest]));
          } else {
            const rawRequests = moduleImports.get(module.resource)!;
            rawRequests.add(rawRequest);
          }
        }
        currentLibraryExpression = undefined;
      });
    };

    compiler.hooks.normalModuleFactory.tap(name, factory => {
      // https://webpack.js.org/configuration/module/#ruletype
      // https://github.com/webpack/webpack/releases/tag/v4.0.0
      // @ts-ignore Incompatible types are being inferred from tapable
      factory.hooks.parser.for('javascript/auto').tap(name, onJavaScriptModule);

      factory.hooks.parser
        .for('javascript/dynamic')
        // @ts-expect-error Incompatible types are being inferred from tapable
        .tap(name, onJavaScriptModule);

      // @ts-expect-error Incompatible types are being inferred from tapable
      factory.hooks.parser.for('javascript/esm').tap(name, onJavaScriptModule);
    });

    compiler.hooks.emit.tapAsync(name, (compilation, callback) => {
      const manifest = buildManifest(compiler, compilation, {
        moduleImports,
        publicPath,
      });
      const json = JSON.stringify(manifest, null, 2);

      compilation.assets[this.filename] = {
        source() {
          return json;
        },
        size() {
          return json.length;
        },
      };

      callback();
    });

    // @ts-expect-error Incompatible types are being inferred from tapable
    compiler.hooks.thisCompilation.tap(name, compilation => {
      // modifies the webpack bootstrap code generated to expose jsonpScriptSrc
      // only needed on Webpack 4.x as Webpack 5+ has official support.
      // use stage 1 to ensure this executes after webpack/lib/web/JsonpMainTemplatePlugin.js
      compilation.mainTemplate.hooks.localVars.tap(
        { name, stage: 1 },
        (source: string) => {
          let modSource = source;
          if (source.includes('function jsonpScriptSrc')) {
            modSource +=
              '\n window.__webpack_get_script_filename__ = jsonpScriptSrc;';
          }

          return modSource;
        }
      );
    });
  }