kukrt
kukrt

Reputation: 2207

how can I load images in base64 string by url-loader in typescript + react (rails5 + webpacker)

example repo https://github.com/github0013/typescript_react

I need to load images in base64 string embeded into tag, but importing image files will raise this error.

TS2307: Cannot find module './Octocat.jpg'.

https://github.com/github0013/typescript_react/commit/6670f3ca74404007ad1ed6e4ab0d111f547ee75d

I am still new to typescript, webpack and react, and I am sure I am confused typescript's import and webpack's.

How do I enable url-loader for images? and is this even valid? https://github.com/github0013/typescript_react/blob/master/config/webpack/environment.js

--
I did try require but it will just return image's path instead of base64 stirng.

// global.d.ts
declare function require(string): string;

Upvotes: 0

Views: 821

Answers (1)

kukrt
kukrt

Reputation: 2207

solved..

webpacker 3.0.2 already had loaders for image files https://github.com/rails/webpacker/tree/v3.0.2/package/loaders https://github.com/rails/webpacker/blob/v3.0.2/package/loaders/file.js

environment.loaders, in rails' config/webpack/environment.js, is just a map, and jpeg png gif are in file loader. https://github.com/github0013/typescript_react/commit/dc97c3aa9f17bc4f3b0210a426aac27092c5ae7f#diff-41713e6b116dc5cc2bbea556a85db322R3

so overriding file loader's test, then add own image loader will use url-loader for jpeg png gif https://github.com/github0013/typescript_react/commit/dc97c3aa9f17bc4f3b0210a426aac27092c5ae7f

after adding the loader, regular image require in typescript will return base64 string.

Upvotes: 1

Related Questions