ts-node and svg import gives: SyntaxError: Unexpected token ‘<'
If you are using TypeScript with ts-node and encounter the error “SyntaxError: Unexpected token ‘<‘” when trying to import SVG files, don’t worry, you’re not alone. This error occurs because ts-node does not natively support importing SVG files. However, there are a couple of solutions you can try to overcome this issue.
Solution 1: Using a Custom Import Declaration
One way to resolve the “SyntaxError: Unexpected token ‘<‘” error is by creating a custom import declaration for SVG files. This involves extending the default TypeScript module resolution behavior to handle SVG imports.
To do this, you will need to install the necessary dependencies:
npm install --save-dev svg-inline-loader
Next, create a file called svg.d.ts
in your project’s root directory with the following content:
// svg.d.ts
declare module '*.svg' {
const content: string;
export default content;
}
This declaration tells TypeScript that when importing an SVG file, it should be treated as a string.
Now, you can import SVG files using the custom declaration:
// app.ts
import svgImage from './path/to/image.svg';
console.log(svgImage);
Make sure to replace ./path/to/image.svg
with the actual path to your SVG file.
Solution 2: Using a Webpack Configuration
If you are using Webpack to bundle your TypeScript code, you can also resolve the “SyntaxError: Unexpected token ‘<‘” error by configuring Webpack to handle SVG imports.
First, install the necessary dependencies:
npm install --save-dev svg-inline-loader
Next, update your Webpack configuration file (e.g., webpack.config.js
) with the following rules:
// webpack.config.js
module.exports = {
// ...
module: {
rules: [
// ...
{
test: /.svg$/,
use: ['svg-inline-loader'],
},
],
},
};
This configuration tells Webpack to use the svg-inline-loader
for handling SVG files.
Now, you can import SVG files in your TypeScript code without encountering the “SyntaxError: Unexpected token ‘<‘” error:
// app.ts
import svgImage from './path/to/image.svg';
console.log(svgImage);
Remember to replace ./path/to/image.svg
with the actual path to your SVG file.
By following either of these solutions, you should be able to import SVG files without encountering the “SyntaxError: Unexpected token ‘<‘” error when using ts-node.
I hope this article helps you resolve the issue. Happy coding!
Leave a Reply