Vue中import与@import的区别及使用场景说明
作者:Wyyyy1024
这篇文章主要介绍了Vue中import与@import的区别及使用场景说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
import与@import的区别及使用场景
import
script中的import是js的语法, 是在js中去引用css文件
(ES6)模块化规范:默认导入语法 import 接收名称 from '模块标识符’
使用
导入组件
import Vue from 'vue'
导入js、css、vue、less等文件
import login from '../views/login/login.vue' import './styles/index.less'
导入第三方插件
import Vant from 'vant'
vue路由懒加载
实现路由懒加载的步骤
1.安装 @babel/plugin-syntax-dynamic-import 包。
npm install --save-dev @babel/plugin-syntax-dynamic-import
2.在 babel.config.js 配置文件中声明该插件。
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk'
}
],
'@babel/plugin-syntax-dynamic-import'
]
}3.将路由改为按需加载的形式,示例代码如下:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
//import具有变量提升机制,使用箭头函数限制作用域,实现懒加载
{ path: '/login', component: ()=> import('路由组件的路径') }
]
const router = new VueRouter({
routes
})
export default router@import
style中的@import是stylus的语法,是在css中引用css文件
使用
导入css样式
@import './icon.less';'
Vue中import from @是什么意思?怎么配置?

一般是在项目构建时生成的文件中定义@对应的属性值,表示将路径进行替换。
比如webpack构建项目,在webpack.config.js中:

而在vite构建的项目中,可以在vite.config.js中定义路径别名:
// vite.config.js 将@替换成./src
resolve: {
alias: [
{ find: /^~/, replacement: '' },
{ find: '@', replacement: resolve(__dirname, './src') }
]
},于是在其他页面中,使用时:
import {xxx} from '@/a/b/c'注意,如果是typescript中,其配置文件在tsconfig.json中。
比如:
// /router/index.js import Home from '@views/home/index.vue'
配置文件中:
// tsconfig.json
{
"compilerOptions": {
"target": xxx;
"baseURL": "./",
"paths": {
"@/*": ["./src/*"]
},这里compilerOptions表示配置typescript文件的编译选项,paths指定了.ts或者.vue文件中import选项时可以使用
import xx from '@xxx'
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
