Adding Images, Fonts, and Files

With Nx, you can import assets directly from your TypeScript/JavaScript code.

1import React from 'react'; 2import logo from './logo.png'; 3 4const Header = () => <img src={logo} alt="Logo" />; 5 6export default Header; 7

This import will be replaced by a string of the image path when the application builds. To reduce the number of network requests, if the image file size is less than 10 kB, then the image will be inlined using data URI instead of a path.

This works in CSS files as well.

1.logo { 2 background-image: url(./logo.png); 3} 4

Adding SVGs

SVG images can be imported using the method described previously.

Alternatively, you can import SVG images as React components using SVGR.

1import React from 'react'; 2import { ReactComponent as Logo } from './logo.svg'; 3 4const Header = () => <Logo title="Logo" />; 5 6export default Header; 7

This method of import allow you to work with the SVG the same way you would with any other React component. You can style it using CSS, styled-components, TailwindCSS, etc. The SVG component accepts a title prop, as well as any other props that the svg element accepts.

Additional configuration may be required

Note that SVGR is enabled by the @nx/webpack plugin by default. For other plugins, you will need to enable it on your own.

SVGR for Next.js

To import SVGs as React components with Next.js, you need to make sure that nx.svgr value is set to true in your Next.js application's next.config.js file:

next.config.js
1// ... 2const nextConfig = { 3 nx: { 4 svgr: true, 5 }, 6}; 7// ... 8module.exports = composePlugins(...plugins)(nextConfig); 9

SVGR for Vite

To import SVGs as React components with Vite, you need to install the vite-plugin-svgr package.

โฏ

npm add -D vite-plugin-svgr

Then, configure Vite as follows:

vite.config.ts
1/// <reference types='vitest' /> 2import { defineConfig } from 'vite'; 3import react from '@vitejs/plugin-react'; 4import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin'; 5import svgr from 'vite-plugin-svgr'; 6 7export default defineConfig({ 8 // ... 9 plugins: [ 10 svgr({ 11 svgrOptions: { 12 exportType: 'named', 13 ref: true, 14 svgo: false, 15 titleProp: true, 16 }, 17 include: '**/*.svg', 18 }), 19 react(), 20 nxViteTsPaths(), 21 // ... 22 ], 23 //... 24}); 25