// .prettierrc.js
const prettierPluginSelfClosingTags = require('./.prettier-plugins/prettier-plugin-self-closing-tags.js');
const prettierPluginTransformImports = require('./.prettier-plugins/prettier-plugin-transform-imports.js');
// prettier-plugin-organize-imports
module.exports = {
singleQuote: true,
plugins: [
// 这个是用于将相对路径变为绝对路径的
prettierPluginTransformImports,
// 这个是用于将标签变为自闭合标签的
prettierPluginSelfClosingTags,
],
};
内部逻辑和 https://github.com/simonhaenisch/prettier-plugin-organize-imports/blob/master/index.js 是一样的,都是增加了 withPluginsPreprocess 然后在 preprocess 做的处理
// prettier-plugin-self-closing-tags
// @ts-expect-error
const { parsers: babelParsers } = require('prettier/parser-babel');
// @ts-expect-error
const { parsers: typescriptParsers } = require('prettier/parser-typescript');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;
function selfClosingTagsPreprocessor(code, options) {
const ast = parser.parse(code, {
plugins: ['typescript', 'jsx'],
sourceType: 'module',
});
traverse(ast, {
JSXElement(path) {
const node = path.node;
// 如果 children 不存在,变为自闭合标签
if (node.children.length === 0) {
node.closingElement = null;
node.openingElement.selfClosing = true;
}
},
});
return generate(ast, {
retainLines: true,
// compact: false,
}).code;
}
const withPluginsPreprocess = (parser) => {
return {
...parser,
/**
* @param {string} code
* @param {import('prettier').ParserOptions} options
*/
preprocess: (code, options) =>
selfClosingTagsPreprocessor(
parser.preprocess ? parser.preprocess(code, options) : code,
options
),
};
};
module.exports = {
parsers: {
babel: withPluginsPreprocess(babelParsers.babel),
'babel-ts': withPluginsPreprocess(babelParsers['babel-ts']),
typescript: withPluginsPreprocess(typescriptParsers.typescript),
},
};