Skip to content

Commit ac49bd5

Browse files
committed
build: support importing SVG as modules
1 parent 6020dd4 commit ac49bd5

4 files changed

+26
-0
lines changed
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* A Jest SyncTransformer that mimics a webpack asset/source module.
3+
*
4+
* i.e. it allows importing a file by transforming the file into a CommonJS
5+
* module that exports the file's contents as a string.
6+
*/
7+
const WebpackAssetSourceTransformer = {
8+
process(sourceText) {
9+
return {
10+
code: `module.exports = ${JSON.stringify(sourceText)};`,
11+
};
12+
},
13+
};
14+
15+
module.exports = WebpackAssetSourceTransformer;

jest.config.js

+3
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,7 @@ module.exports = {
1414
maxWorkers: 1,
1515
testPathIgnorePatterns: ["/node_modules/", ".mock."],
1616
setupFilesAfterEnv: ["<rootDir>/jest-setup.ts"],
17+
transform: {
18+
"\\.svg$": "<rootDir>/jest-webpack-asset-source-transformer",
19+
},
1720
};

src/webpack-assets.d.ts

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
declare module "*.svg" {
2+
const source: string;
3+
export default source;
4+
}

webpack-config.ts

+4
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ const config: Configuration = {
2020
test: /\.css$/,
2121
use: ["style-loader", "css-loader", "postcss-loader"],
2222
},
23+
{
24+
test: /\.svg$/,
25+
type: "asset/source",
26+
},
2327
],
2428
},
2529
resolve: {

0 commit comments

Comments
 (0)