19730

Vue项目创建与配置

本文简单介绍下vue-cli2和vue-cli3的项目创建及基础配置

VUE-CLI2

#创建项目
vue init webpack your_program_name

#添加扩展包
yarn add axios
yarn add sass-loader -D

#安装package.json中的依赖
yarn

#运行项目
yarn dev

#构建项目
yarn build

全局变量

在webpack配置文件中设置

{
    plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            SERVER_URL: "http://a.com",
          }
        }),
    ]
}

VUE-CLI3

#安装脚手架
yarn global add @vue/cli

#创建项目
vue create your_program_name

#添加扩展包
yarn add axios
yarn add sass-loader -D

#安装package.json中的依赖
yarn

#运行项目
yarn serve

#构建项目
yarn build

全局变量

vue-cli3添加全局变量至少有两种可行的方式:

1、在根目录创建 .env 或 .env.production 文件
VUE_APP_BASE_API = 'http://your_domain.com'

该方式添加全局变量,缺点是:必须带VUE_APP_前缀

2、在vue.config.js文件中通过 chainWebpack 的方式
//vue.config.js

const merge = require('webpack-merge')
const _process = require('./process')

function _format_env(env) {
  //方法一
  // for (const key in env) {
  //   if (env.hasOwnProperty(key)) {
  //     env[key] = JSON.stringify(env[key])
  //   }
  // }
  //方法二
  Object.keys(env).forEach(key => {
    env[key] = JSON.stringify(env[key])
  })
  return {
    'process.env': env
  }
}

module.exports = {
  runtimeCompiler: true,
  publicPath: '/',
  chainWebpack: config => {
    config.plugin('define').use(require('webpack/lib/DefinePlugin'), [
      _format_env(merge(process.env, require('./process')))
    ])
  }
}

process.js文件内容如下

//process.js

'use strict'
module.exports = {
  SERVER_URL: "http://a.com",
  LOCAL_HOST: "127.0.0.1",
  LOCAL_PORT: "8080",
  LOCAL_SSL: false
}

vue跨域配置

//vue.config.js

devServer: {
    // overlay: {
    //   warnings: true,
    //   errors: true
    // },
    open: true,
    host: _process.LOCAL_HOST,
    port: _process.LOCAL_PORT,
    https: _process.LOCAL_SSL,
    hotOnly: false,
    proxy: {
      '/v': {
        target: _process.SERVER_URL,
        changeOrigin: true,
        // pathRewrite: {'^/v': ''},
        secure: _process.SERVER_URL.includes('https'),
      }
    }
  }
文章作者:DOTATONG
发布日期:2018-05-06

评论

暂无

添加新评论