我正在使用SVGR的CLI工具尝试创建一个MUI兼容的React图标模板,以便在Next中使用。根据他们的文档:
我尝试设计了一个类似于这样的快速编织项目:
起初,我以为这是因为我缺少一个带有
更新:我现在知道这绝对是@svgr中(或者我的本地)的某些东西强制使用ES6导入语法。使用
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>
您可以看到它们指向项目的defaultTemplate.ts文件,其内容如下:
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};
`
}
我尝试设计了一个类似于这样的快速编织项目:
/
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"
}
}
模板/
mui.template.ts
(与默认模板相同)
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"
}
但无论我做什么,它都抱怨我:
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.
起初,我以为这是因为我缺少一个带有
{"type": "module"}
的package.json
文件,然后我读了一些关于将其变成.mts
文件或者一些错误依赖项的东西,但我尝试过的所有方法似乎都不起作用。我该如何使此模板文件像一个模块一样运行?
更新:我现在知道这绝对是@svgr中(或者我的本地)的某些东西强制使用ES6导入语法。使用
require()
和module.exports =
重写可以解决问题。只需要找出如何强制其以ES6模式运行即可。