Vue.js 使用不同的环境变量构建 [英] Vue.js build with different environment variables

查看:24
本文介绍了Vue.js 使用不同的环境变量构建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 Vue.js 使用了官方 Webpack 模板.它对不同的环境使用单独的配置.他们提供测试、开发和生产.但是,我需要另一台,因为我们有两台生产服务器(一台生产服务器和一台暂存服务器).

I've used official Webpack template for Vue.js. It uses separate configuration for different environments. They offer test, development and production. However, I need another one as we have two production servers (one production and one staging).

为不同的生产环境设置不同的配置的最佳实践是什么?我会想到像 npm run build --URL:http://some-url.com --PORT:80 ... 之类的东西.

What is the best practice to have different configurations for different production environments? I would think of something like npm run build --URL:http://some-url.com --PORT:80 ....

欢迎任何建议!

推荐答案

这更像是一个 webpack 问题而不是 Vue.js,我想分享我们之前处理不同构建文件和环境的设置.首先,我们将配置保存在单独的文件夹中.

This is more like a webpack question rather then Vue.js, I wanna share our previous setup for handling different build files and environments. first of all, we keep our config in separated folder.

config/index.js

config/index.js

// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')

const CDN = 'https://cdnURL.com/'

module.exports = {
  build: {
    env: require('./prod.env'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: CDN,
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    productionBundleAnalyze: process.env.ANALYZE ? true : false
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: process.env.npm_package_config_proxy,
        logLevel: 'debug',
        changeOrigin: true,
        onProxyRes(proxyRes, req, res) {
          // http-proxy-middleware
          proxyRes.headers['Content-Type'] = proxyRes.headers['content-type']
          delete proxyRes.headers['content-type']
        }
      }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  },
  projects: {
    main: {
      entry: './packages/home/index.js',
      devPath: 'main.html',
      target: 'web',
      buildPath: path.resolve(__dirname, '../dist/index.html'),
      testPath: '../packages/home/__test__/index.js'
    },
    desktop: {
      entry: './packages/desktop/index.js',
      devPath: 'desktop.html',
      target: 'electron-renderer',
      buildPath: path.resolve(__dirname, '../../static/desktop.html'),
      assetsRoot: path.resolve(__dirname, '../../'),
      assetsSubDirectory: 'static',
      assetsPublicPath: '../',
      testPath: '../packages/desktop/__test__/index.js'
    },
    login: {
      entry: './packages/login/index.js',
      devPath: 'login.html',
      target: 'web',
      buildPath: path.resolve(__dirname, '../dist/login.html'),
      testPath: '../packages/login/__test__/index.js'
    },
    setting: {
      entry: './packages/setting/index.js',
      devPath: 'setting.html',
      target: 'web',
      buildPath: path.resolve(__dirname, '../dist/setting.html'),
      testPath: '../packages/setting/__test__/index.js'
    },
    playground: {
      entry: './packages/playground/index.js',
      target: 'web'
    }
  }
}

config/dev.env.js

config/dev.env.js

var merge = require('webpack-merge')
var prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_ROOT: '"/api"'
})

config/prod.env

config/prod.env

module.exports = {
  NODE_ENV: '"production"',
  API_ROOT: '"http://test.example.co/api"'  //staging server
  // API_ROOT: '"http://127.0.0.1:8787/api"'  //mock-up server
}

如果我们想工作,我们在这里更改 API 根目录.

incase of where we wanna work we change API root in here.

和我们的 webpack.base.conf.js 看起来像这样.构建/webpack.base.conf.js

and our webpack.base.conf.js look like this. build/webpack.base.conf.js

var path = require('path')
var config = require('../config')
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../')

const isProduction = process.env.NODE_ENV === 'production'

module.exports = {
  entry: utils.entrys(),
  output: {
    path: config.build.assetsRoot,
    publicPath: isProduction ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'src': path.resolve(__dirname, '../src'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components')
    },
    unsafeCache: true
  },
  target: config.projects[process.env.npm_package_config_dev].target,
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          postcss: [
            require('postcss-cssnext')(),
            require('lost')()
          ],
          cssModules: {
            localIdentName: isProduction ? '[path][name]---[local]---[hash:base64:5]' : '[path][name]--[local]',
            camelCase: true
          },
          loaders: Object.assign({}, utils.cssLoaders()),
          preLoaders: {
            html: 'inline-svg-loader'
          }
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: projectRoot,
        exclude: /node_modules/,
        query: {
          cacheDirectory: true
        }
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.html$/,
        loader: 'vue-html-loader'
      },
      {
        test: /\.(png|jpe?g|gif)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  }
}

最后我们的 package.json 看起来像这样

and finally our package.json is look like this

...
...
...
    "scripts": {
      "dev": "webpack-dashboard -- node build/dev-server.js",
      "dev:login": "npm config set mesh:dev login && npm run dev",
      "dev:setting": "npm config set mesh:dev setting && npm run dev",
      "dev:main": "npm config set mesh:dev main && npm run dev",
      "dev:desktop": "npm config set mesh:dev desktop && node build/dev-server.js",
      "dev:playground": " npm config set mesh:dev playground && cross-env PORT=9000 npm run dev"
     }
...
...
...

在使用共享组件的同时,我们使用此设置将我们的应用程序捆绑到电子、网络和 webkit.

we used this setup for bundle our app for electron, web, and webkit while using shared components.

但后来我们遇到了剥落的问题.如果您需要更多模块,我们开始使用 lerna.我建议你检查一下.

but still later on we had issue of scalling. and we started to use lerna if you need something more moduler. I recommend you to check that one out.

最好的问候.

这篇关于Vue.js 使用不同的环境变量构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆