Vue + webpack project import path and path alias

  import path

        In Vue projects, we often encounter the following ways of passing references:

import './plugins/element.js'

import '../router';

import '@/scss/common/var';

import 'common/flexible.js'

        1. ./ indicates   the current directory
        2. ../ indicates the parent directory
        3. @/ is the path alias set by  webpack  , what path it represents, if the project is created with vue-cli2 scaffolding, it depends on the build folder of webpack How to configure @ in webpack.base.conf.js , if it is a project created with v ue-cli3, you can check it in the vue.config.js file .

resolve: {
  extensions: ['.js', '.vue', '.json'],
  alias: {
    'vue$': 'vue/dist/vue.esm.js',
    '@': resolve('src'),
  }
}

        The above example  @/  represents the path to the src folder.

        4. If there is no leading " /", " ./", " ../" or " @/ " to indicate the file, the path is:  node_modules  folder. The Vue project uses npm to install the plug-in. After installation, the plug-in is placed in  the node_modules folder of the project, so when importing the plug-in, take  the vue-quill-editor plug-in as an example, it should be written like this:

import VueQuillEditor from 'vue-quill-editor'

Vue path aliases

        When we write vue , we need to introduce many components or  css  styles. When we have more and more files and more and more layers, it is more troublesome to import, and we have to write a lot of " .../.../ ", for example: "  import '../../../plugins/element .js'  ", for the convenience of writing, we can set an alias for the vue path to save code input times and improve development efficiency.

Create a new vue.config.js file         in the project root path (create it if it does not exist), and then enter the following code in the file:

const path = require('path');        // 引入path模块
function resolve(dir){    // 声明一个函数,调用函数的时候传入相对路径
  return path.join(__dirname,dir)    // path.join(__dirname)设置绝对路径
}
module.exports = defineConfig({
  chainWebpack:(config)=>{
    config.resolve.alias
      // .set('路径别名', resolve('vue.config文件的相对路径'))
      .set('@', resolve('src'))
      .set('assets', resolve('src/assets'))
      .set('components', resolve('src/components'))
      .set('common', resolve('src/common'))
      .set('network', resolve('src/network'))
  }
})

        After modifying vue.config.js  , you need to re-run the project to take effect. Finally, if you want to load the logo image in assets under the src file  , you can directly import it like this :

import logo from 'assets/logo.png'

Guess you like

Origin blog.csdn.net/weixin_42754922/article/details/123760406