123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- const originalFetch = global.fetch;
- delete global.fetch;
- const { SourceMapConsumer, SourceMapGenerator, SourceNode } = require('source-map');
- const { Template } = require('webpack');
- function getIdentitySourceMap(source, resourcePath) {
- const sourceMap = new SourceMapGenerator();
- sourceMap.setSourceContent(resourcePath, source);
- source.split('\n').forEach((line, index) => {
- sourceMap.addMapping({
- source: resourcePath,
- original: {
- line: index + 1,
- column: 0,
- },
- generated: {
- line: index + 1,
- column: 0,
- },
- });
- });
- return sourceMap.toJSON();
- }
- function getTemplate(fn) {
- return Template.getFunctionContent(fn).trim().replace(/^ {2}/gm, '');
- }
- const RefreshSetupRuntime = getTemplate(require('./RefreshSetup.runtime')).replace(
- '$RefreshRuntimePath$',
- require.resolve('react-refresh/runtime').replace(/\\/g, '/')
- );
- const RefreshModuleRuntime = getTemplate(require('./RefreshModule.runtime'));
- function ReactRefreshLoader(source, inputSourceMap, meta) {
- const callback = this.async();
-
- async function _loader(source, inputSourceMap) {
- if (this.sourceMap) {
- let originalSourceMap = inputSourceMap;
- if (!originalSourceMap) {
- originalSourceMap = getIdentitySourceMap(source, this.resourcePath);
- }
- const node = SourceNode.fromStringWithSourceMap(
- source,
- await new SourceMapConsumer(originalSourceMap)
- );
- node.prepend([RefreshSetupRuntime, '\n\n']);
- node.add(['\n\n', RefreshModuleRuntime]);
- const { code, map } = node.toStringWithSourceMap();
- return [code, map.toJSON()];
- } else {
- return [[RefreshSetupRuntime, source, RefreshModuleRuntime].join('\n\n'), inputSourceMap];
- }
- }
- _loader.call(this, source, inputSourceMap).then(
- ([code, map]) => {
- callback(null, code, map, meta);
- },
- (error) => {
- callback(error);
- }
- );
- }
- module.exports = ReactRefreshLoader;
- if (originalFetch) {
- global.fetch = originalFetch;
- }
|