【Vue】为什么在 vue 中不能使用 import()语法?
我采用的是iview组件库的构建工具构建的项目,在使用过程中发现 import() 这个东西不能用!
报错如上图,
代码如下
项目内的.babelrc如下
{
"presets": [
[
"es2015",
"stage-3"
]
]
}
项目配置如下
{
"name": "ji",
"version": "1.0.0",
"description": "项目",
"main": "index.js",
"scripts": {
"init": "webpack --progress --config webpack.dev.config.js",
"dev": "webpack-dev-server --content-base ./ --open --inline --hot --compress --history-api-fallback --config webpack.dev.config.js",
"build": "webpack --progress --hide-modules --config webpack.prod.config.js",
"lint": "eslint --fix --ext .js,.vue src"
},
"repository": {
"type": "git",
"url": ""
},
"author": "",
"license": "MIT",
"dependencies": {
"axios": "^0.15.3",
"clipboard": "^1.5.12",
"echarts": "^3.4.0",
"html2canvas": "^0.5.0-beta4",
"iview": "^2.0.0-rc.13",
"js-cookie": "^2.1.3",
"lodash": "^4.17.4",
"rasterizehtml": "^1.2.4",
"vue": "^2.2.6",
"vue-i18n": "^5.0.3",
"vue-ls": "^2.3.3",
"router" title="vue-router">vue-router": "^2.3.1",
"vuex": "^2.2.1"
},
"devDependencies": {
"autoprefixer-loader": "^2.0.0",
"babel": "^6.23.0",
"babel-core": "^6.23.1",
"babel-loader": "^6.2.4",
"babel-plugin-transform-runtime": "^6.12.0",
"babel-preset-es2015": "^6.9.0",
"babel-preset-stage-3": "^6.24.1",
"babel-runtime": "^6.11.6",
"css-loader": "^0.23.1",
"eslint": "^3.12.2",
"eslint-plugin-html": "^1.7.0",
"extract-text-webpack-plugin": "^2.0.0",
"file-loader": "^0.8.5",
"html-loader": "^0.3.0",
"html-webpack-plugin": "^2.28.0",
"less": "^2.7.1",
"less-loader": "^2.2.3",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"vue-hot-reload-api": "^1.3.3",
"vue-html-loader": "^1.2.3",
"vue-loader": "^11.0.0",
"vue-style-loader": "^1.0.0",
"vue-template-compiler": "^2.2.1",
"webpack": "^2.2.1",
"webpack-dev-server": "^2.4.1",
"webpack-merge": "^3.0.0"
}
}
下面的东西麻烦看下
import http://es6.ruanyifeng.com/?se...
回答
上面的回答好像都有点文不对题。
解决方法:
先安装babel用来编译import方法的模块 babel-plugin-syntax-dynamic-import
cnpm install -D babel-plugin-syntax-dynamic-import
在.bablerc中引入syntax-dynamic-import插件
{ "presets": ["es2015", "stage-3"],
"plugins": ["syntax-dynamic-import"]
}
给两个参考链接:
import 目前只能在顶级域中用,不能在函数、条件分支里用
import() 是 webpack 里用于 code splitting 的吧,感觉应该可以用才对。
用 vue-cli 使用最新 webpack 项目模板创建一个项目,试下是否可用,如果可用的话,比较两个项目的配置有哪些差异
import cc from "./aa.vue"
将babel配置改为如下,
然后安装依赖
babel-preset-env
{ "presets": [
[
"env",
{
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}
],
"stage-2"
],
]
很显然,你使用的不对。
import() 这个叫做异步组件,简单说就是需要的时候加载。
所以,你应该在你使用这个组件的地方,也就是父组件内引用,而不是在组件里面直接 import()
// 这个异步组件// async.vue
export default {
name: 'async'
}
// 使用异步组件<template>
<div id="app">
<async></async>
</div>
</template>
<script>
export default {
name: 'app',
components: {
async: () => import('./async')
}
}
</script>
你这是异步的import
,Babel
需要另外再加一个插件才能用:
syntax-dynamic-import
楼上 shenfq 的回答正解,遇到这种问题我的建议就是看官网,webpack https://doc.webpack-china.org...
webpack import动态导入
node环境目前还不支持import/export
以上是 【Vue】为什么在 vue 中不能使用 import()语法? 的全部内容, 来源链接: utcz.com/a/72954.html