react-refresh-webpack-plugin icon indicating copy to clipboard operation
react-refresh-webpack-plugin copied to clipboard

ReactRefresh + Custom plugin for modification source code = broken source code

Open romanlex opened this issue 2 years ago • 0 comments

I found two issues with my custom Webpack Plugin for modification source code of module

Apply function from plugin:

apply(compiler) {
  compiler.hooks.entryOption.tap(PLUGIN_NAME, (context, entry) => this.onEntryOption(context, entry))

  compiler.hooks.normalModuleFactory.tap(PLUGIN_NAME, (factory) => {
    factory.hooks.parser.for('javascript/auto').tap(PLUGIN_NAME, (parser) => {
      // collect parsers
      this.extractParser(parser)
    })
  })

  compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
    compilation.hooks.finishModules.tapAsync(PLUGIN_NAME, (modules, done) => {
      // Collect needed modules and create map for replace
      this.onFinishModules(modules)
      done()
    })
    compilation.hooks.optimizeDependencies.tap(PLUGIN_NAME, (modules) => {
      // replace source code
      const { options } = this
      if (!options.to) return

      for (const module of modules) {
        if (!module._source || !module._source._valueAsString) continue

        if (!new RegExp(options.to, 'gm').test(module._source._valueAsString)) continue

        const stringifyedObject = ....
        
        let newSource = module._source.source().replace(new RegExp(to, 'gm'), stringifyedObject)

        module._source = new sources.RawSource(newSource)
      }
    })
  })
}

By default with ReactRefreshPlugin I have destroyed js code image

I'm tryed add exclude option for plugin and got another problem with source code

new ReactRefreshWebpackPlugin({
    exclude: [/node_modules/, /constants\/webpack/],
})

image

In both cases I have destroyed source code with custom webpack plugin

in production mode without RefreshPlugin all work correctly

romanlex avatar Feb 14 '23 14:02 romanlex