What does the @ character do in javascript import?

For example:

import Component from '@/components/component' 

In the code I'm looking at, it behaves like ../ , rising one level in the directory relative to the file path, but I would like to know in more detail what it does. Unfortunately, I can not find the documentation on the Internet due to the problem of finding characters.

+18
javascript
Mar 10 '17 at 5:49
source share
3 answers

The meaning and structure of the module identifier depends on the module or module loader. The boot module is not part of the ECMAScript specification. In terms of the JavaScript language, the module identifier is completely opaque. So it really depends on which bootloader / provider module you are using.

You most likely have something like babel-plugin-root-import in your webpack / babel configuration.

This basically means that from the root of the project ... it avoids the need to write things like import Component from '../../../../components/component'

Edit: One of the reasons it exists is that import Component from 'components/component' does not do this, but instead looks in the node_modules folder

+36
Mar 10 '17 at 5:56 on
source share

Know this, but I was not exactly sure how it was determined, so I looked at it, came in, went deep and finally found it in my Vue-CLI ( Vue.js ) Webpack configuration was generated

 resolve: { extensions: ['.js', '.vue', '.json'], alias: { '@': path.join(__dirname, '..', dir) } }, 

so this is an alias that in this case points to the vu-cli root generated by the project src directory

+18
May 30 '17 at 1:05 a.m.
source share

To make Ben more complete:

First you need to add babel-plugin-root-import to devDependencies in package.json (if using yarn : yarn add devDependencies --dev ). Then in .babelrc add the following lines to the plugins :

 "plugins": [ [ "babel-plugin-root-import", { "rootPathPrefix": "@" } ] ] 

Now you can use @ . For example:

Instead

import xx from '../../utils/somefile'

You can

import xx from '@/utils/somefile'

+5
Sep 17 '17 at 6:42 on
source share



All Articles