From aae3851d5971f267424f1ee2184cbe3e77d58950 Mon Sep 17 00:00:00 2001 From: Martin Fournier Date: Wed, 19 Jan 2022 10:51:36 -0500 Subject: [PATCH] Add webpack file-loader to handle images It lets us bundle static files such as images. Allows us to `imports img from "./img.png"` to retrieve an image's path. Note that we'll have to add other entries in the global.d.ts file if we want to handle other extensions than .png. Adds mocks to Jest tests so that we don't fail tests when loading static assets. --- jest.config.js | 4 ++++ package.json | 1 + src/@types/global.d.ts | 6 ++++++ test/__mocks__/fileMock.js | 1 + test/__mocks__/styleMock.js | 0 webpack.config.js | 8 ++++++++ 6 files changed, 20 insertions(+) create mode 100644 test/__mocks__/fileMock.js create mode 100644 test/__mocks__/styleMock.js diff --git a/jest.config.js b/jest.config.js index 2be488205..af66d7809 100644 --- a/jest.config.js +++ b/jest.config.js @@ -8,4 +8,8 @@ module.exports = { '.cypress', 'node_modules', 'dist', ], testEnvironment: "jsdom", + moduleNameMapper: { + "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "/test/__mocks__/fileMock.js", + "\\.(css|less)$": "/test/__mocks__/styleMock.js" + } }; diff --git a/package.json b/package.json index ab72e91fd..62e5e1318 100644 --- a/package.json +++ b/package.json @@ -71,6 +71,7 @@ "electron": "^14.0.2", "electron-packager": "^15.4.0", "eslint": "^7.24.0", + "file-loader": "^6.2.0", "fork-ts-checker-webpack-plugin": "^6.3.3", "html-webpack-plugin": "^3.2.0", "http-server": "^13.0.1", diff --git a/src/@types/global.d.ts b/src/@types/global.d.ts index 2eed8c77e..8840ea1b8 100644 --- a/src/@types/global.d.ts +++ b/src/@types/global.d.ts @@ -1,2 +1,8 @@ // Defined by webpack on startup or compilation declare let __COMMIT_HASH__: string; + +// When using file-loader, we'll get a path to the resource +declare module "*.png" { + const value: string; + export default value; +} diff --git a/test/__mocks__/fileMock.js b/test/__mocks__/fileMock.js new file mode 100644 index 000000000..86059f362 --- /dev/null +++ b/test/__mocks__/fileMock.js @@ -0,0 +1 @@ +module.exports = 'test-file-stub'; diff --git a/test/__mocks__/styleMock.js b/test/__mocks__/styleMock.js new file mode 100644 index 000000000..e69de29bb diff --git a/webpack.config.js b/webpack.config.js index 2b72bb10e..4a62292dd 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -156,6 +156,14 @@ module.exports = (env, argv) => { test: /\.s?css$/, use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"], }, + { + test: /\.(png|jpe?g|gif|jp2|webp)$/, + loader: 'file-loader', + options: { + name: '[contenthash].[ext]', + outputPath: 'dist/images', + }, + }, ], }, optimization: {