下面实例是基于 Taro框架使用React开发微信小程序的实现自动格式化和代码规范的配置教程
安装 ESLint 和 Prettier 插件: 在微信开发者工具的插件市场中搜索并安装 ESLint 和 Prettier 插件。
module.exports = {
extends: ['eslint:recommended', 'plugin:prettier/recommended'],
env: {
browser: true,
es6: true,
},
rules: {
'prettier/prettier': 'error',
},
};
.prettierrc
文件,配置你的代码格式化规则,例如:{
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 80
}
{
"editor.formatOnSave": true, // 保存时自动格式化
"editor.defaultFormatter": "esbenp.prettier-vscode", // 设置 Prettier 作为默认格式化工具
"eslint.autoFixOnSave": true, // 保存时自动修复 ESLint 错误
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"html",
"vue",
"wxss" // 确保 wxss 文件也能被 ESLint 检查
],
"editor.glyphMargin": false,
"editor.fontFamily": "Menlo",
"editor.fontSize": 16,
"editor.lineHeight": 32,
"files.autoSave": "off",
"editor.wordWrap": "on",
"editor.minimap.enabled": false,
"editor.insertSpaces": true,
"editor.tabSize": 2,
"workbench.editor.enablePreview": true,
"workbench.editor.enablePreviewFromQuickOpen": true,
"editor.detectIndentation": false,
"workbench.editorAssociations": [
{
"filenamePattern": "project.miniapp.json",
"viewType": "settingsEditor.settingsedit"
}
],
"files.eol": "auto",
"[typescriptreact]": {
"editor.defaultFormatter": "vscode.typescript-language-features"
},
"notebook.kernelProviderAssociations": [],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"html.format.contentUnformatted": ""
}
这样,保存文件时就可以自动按照 ESLint 和 Prettier 的规则进行格式化,保持代码的一致性和规范性。