Vue CLI2升级至Vue CLI3的方法步骤

2020-06-13 10:35:13易采站长站整理

默认情况下,JetBrains 系列的 IDE 无法对 Vue 指定的

@
符号进行正确的路径识别。此时我们可以在项目根文件夹下创建
webpack.config.js
文件,并写入:


module.exports = {
resolve: {
alias: {
'@': require('path').resolve(__dirname, 'src')
}
}
};

之后,在 IDE 中指定该文件路径:

之后,IDE 便能正确识别

@
所表示的路径了。

5. 添加全局 Scss 文件

在前端项目中,经常会用到相同的主题色。此时,我们需要存储这些变量,且将其全局引入。

在 Vue CLI 3 中,我们可以在根目录下新建一个

vue.config.js
文件,写入如下内容:


module.exports = {
css: {
loaderOptions: {
sass: {
data: `@import "@/styles/settings.scss";`
}
}
}
};

此时,

settings.scss
该文件中的变量值便能在任意 Vue 组件中使用了。

当然,如果要在

.vue
文件中使用 SCSS 语法,需要在
<style>
标签中增加如下属性:


<style scoped lang="scss" type="text/scss">

</style>

6. 调整 ESLint 配置

ESLint 对未使用的变量和函数参数都做了限制,但原项目中确实有些地方需要保留这些 “暂时用不上” 的变量,因而这里对默认的 ESLint 设置做了调整,即修改

.eslintrc.js
文件:


{
...

rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'vue/no-unused-vars': 'off',
'vue/no-empty-pattern': 'off'
},

...
}

7. Compiler 模式变更为 Runtime 模式

在升级至 Vue CLI 3 之后,直接运行可能会出现如下报错:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

(found in <Root>)

这是因为 3.x 版本默认使用的是运行时模式,需要对

main.js
文件进行修改:


new Vue({
router,
store,
render: h => h(App)