I'm using SVGR's CLI tool to try to create a template for a MUI-compatible React icon that works with Next. Per their docs:
Template
Specify a template file (CLI) or a template function (API) to use. For an example of template, see the default one.
Default CLI Override API Override
basic template --template template: <func>
You can see they point to the project's defaultTemplate.ts file, which looks like this:
import type { Template } from './types'
export const defaultTemplate: Template = (variables, { tpl }) => {
return tpl`
${variables.imports};
${variables.interfaces};
const ${variables.componentName} = (${variables.props}) => (
${variables.jsx}
);
${variables.exports};
`
}
I've tried to lay out a quick yarn project that looks like this:
/
package.json
{
"devDependencies": {
"@babel/core": "^7.0.0",
"@svgr/webpack": "^6.2.1",
"babel-loader": "^8.0.6",
"webpack": "^5.68.0"
},
"scripts": {
"build": "npx @svgr/cli --typescript --memo --svg-props preserveAspectRatio='xMidYMid meet' --template ./template --out-dir dist -- icons"
}
}
template/
mui.template.ts
(Same as the default template)
package.json
{
"name": "mui.template",
"version": "1.0.0",
"type": "module",
"description": "MUI icon template for SVGR",
"main": "mui.template.ts",
"author": "Me",
"license": "MIT"
}
But no matter what I do, it complains at me:
Error when loading "--template": ./template
.../next/template/mui.template.ts:1
import { Template } from '@svgr/babel-plugin-transform-svg-component';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1026:15)
at Module._compile (node:internal/modules/cjs/loader:1061:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Option.parseArg (/.../.npm/_npx/0b534691f7d2b666/node_modules/@svgr/cli/dist/index.js:317:22)
at handleOptionValue (/.../.npm/_npx/0b534691f7d2b666/node_modules/commander/lib/command.js:545:24)
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
At first I assumed this was because I was missing a package.json with {"type": "module"}, then I read some stuff about making it a .mts file, or perhaps some incorrect dependencies, but nothing I've tried seems to be working. How can I make this template file behave like a module?
Update: I know now that this is definitely something in @svgr (or my local?) that is forcing < ES6 import syntax. Rewriting with require() and module.exports = works. Just have to figure out how to force it to run in ES6 mode.