文件中使用相对路径,相对不友好, 代码格式化提交的时候消息不明确

vite.config.js

  1. import { defineConfig } from 'vite'
  2. import aliasPath from './aliasPath'
  3. export default defineConfig({
  4. resolve: {
  5. // alias: aliasPath.resolve.alias // Object
  6. alias: aliasPath // Array
  7. },
  8. })

alias Arrray

解决 less @~ 路径报错
image.png

  1. const path = require('path');
  2. const resolve = (url) => path.resolve(__dirname, url);
  3. module.exports = [
  4. { find: /^~/, replacement: '' },
  5. {
  6. find: '@',
  7. replacement: resolve('src'),
  8. },
  9. {
  10. find: '@components',
  11. replacement: resolve('src/components'),
  12. },
  13. {
  14. find: '@utils',
  15. replacement: resolve('src/utils'),
  16. },
  17. {
  18. find: '@layouts',
  19. replacement: resolve('src/layouts'),
  20. },
  21. {
  22. find: '@routes',
  23. replacement: resolve('src/routes'),
  24. },
  25. {
  26. find: '@constants',
  27. replacement: resolve('src/constants'),
  28. },
  29. {
  30. find: '@models',
  31. replacement: resolve('src/models'),
  32. },
  33. {
  34. find: '@locales',
  35. replacement: resolve('src/locales'),
  36. }
  37. ]

alias Object

  1. const path = require('path');
  2. const resolve = (url) => path.resolve(__dirname, url);
  3. module.exports = {
  4. context: resolve('./'),
  5. resolve: {
  6. 'alias': {
  7. // 如果报错__dirname找不到,需要安装 @types/node
  8. // "@": path.resolve(__dirname, "src"),
  9. '@': resolve('src'),
  10. '@const': resolve('src/const'),
  11. '@components': resolve('src/components'),
  12. '@models': resolve('src/models'),
  13. '@routes': resolve('src/routes'),
  14. '@utils': resolve('src/utils'),
  15. '@layouts': resolve('src/layouts'),
  16. '@locales': resolve('src/locales'),
  17. },
  18. },
  19. };

如果报错__dirname找不到,需要安装 @types/node

  • ts开发场景下,会报这个错,本地识别 node环境
  • 使用 import path from ‘path’ 进行引入
  • 不要再使用 const path = require(‘path’)
    1. yarn add @types/node --save-dev