rsnext/packages/react-refresh-utils/loader.ts
Tim Neutkens 62b1704e41
Add support for "type": "module" in package.json (#33637)
- [x] Add failing test for development / production
- [x] Add failing test for client-side JavaScript
- [x] Write `.next/package.json` with `"type": "commonjs"
- [x] Fix issue with client-side JavaScript showing `module` is not defined

Production works after these changes. Development breaks on module not existing because of the Fast Refresh loader. Working with @sokra to add alternatives to what is being used in the loader to webpack so that it can be updated.

Fixes #23029, Fixes #24334



## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
2022-02-15 16:24:11 +00:00

34 lines
1,002 B
TypeScript

import type { LoaderDefinition } from 'webpack'
import RefreshModuleRuntime from './internal/ReactRefreshModule.runtime'
let refreshModuleRuntime = RefreshModuleRuntime.toString()
refreshModuleRuntime = refreshModuleRuntime
.slice(
refreshModuleRuntime.indexOf('{') + 1,
refreshModuleRuntime.lastIndexOf('}')
)
// Given that the import above executes the module we need to make sure it does not crash on `import.meta` not being allowed.
.replace('global.importMeta', 'import.meta')
let commonJsrefreshModuleRuntime = refreshModuleRuntime.replace(
'import.meta.webpackHot',
'module.hot'
)
const ReactRefreshLoader: LoaderDefinition = function ReactRefreshLoader(
source,
inputSourceMap
) {
this.callback(
null,
`${source}\n\n;${
// Account for commonjs not supporting `import.meta
this.resourcePath.endsWith('.cjs')
? commonJsrefreshModuleRuntime
: refreshModuleRuntime
}`,
inputSourceMap
)
}
export default ReactRefreshLoader