Skip to content
This repository was archived by the owner on Mar 5, 2022. It is now read-only.

Commit 12d859e

Browse files
committed
feat: redirect images to __root
1 parent 6fb6fc2 commit 12d859e

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

plugins/cra-v3/file-preprocessor.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,23 @@ const getWebpackOptions = opts => {
1818
findWebpack.cleanForCypress(opts, webpackOptions)
1919
debug('claned webpack options: %o', webpackOptions)
2020

21+
// we need to handle static images and redirect them to
22+
// the existing files. Cypress has fallthrough static server
23+
// for anything like "/_root/<path>" which is perfect - because
24+
// importing a static image gives us that <path>!
25+
// insert our loader first before any built-in loaders kick in
26+
const loaderRules = webpackOptions.module.rules.find(rule =>
27+
Array.isArray(rule.oneOf),
28+
)
29+
if (loaderRules) {
30+
debug('found oneOf rule %o', loaderRules.oneOf)
31+
debug('adding our static image loader')
32+
loaderRules.oneOf.unshift({
33+
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, /\.svg$/],
34+
loader: require.resolve('./redirect-resource'),
35+
})
36+
}
37+
2138
const options = {
2239
webpackOptions,
2340
watchOptions: {},

plugins/cra-v3/redirect-resource.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
const debug = require('debug')('cypress-react-unit-test')
2+
const path = require('path')
3+
4+
/**
5+
* User code:
6+
* import image from './path/to/image.png'
7+
* <img src={image} />
8+
* This loader will return you
9+
* image is "/__root/path/to/image.png"
10+
* <img src={image} />
11+
*/
12+
function staticResourceLoader() {
13+
debug('loading static resource %s', this.resourcePath)
14+
debug('cwd', process.cwd())
15+
const relativeResourcePath = path.relative(process.cwd(), this.resourcePath)
16+
debug('relative resource', relativeResourcePath)
17+
const staticResourceUrl = `/__root/${relativeResourcePath}`
18+
debug('static resource url: %s', staticResourceUrl)
19+
20+
return `module.exports = ${JSON.stringify(staticResourceUrl)}`
21+
}
22+
23+
module.exports = staticResourceLoader

0 commit comments

Comments
 (0)