Vue.js使用不同的环境变量构建

时间:2017-06-01 14:28:18

标签: webpack vue.js

我已将official Webpack template用于Vue.js.它对不同的environments使用单独的配置。他们提供测试,开发和生产。但是,我需要另一个,因为我们有两个生产服务器(一个生产和一个分期)。

为不同的生产环境提供不同配置的最佳做法是什么?我会想到像npm run build --URL:http://some-url.com --PORT:80 ...这样的东西。

欢迎任何建议!

3 个答案:

答案 0 :(得分:18)

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

配置/ 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'
    }
  }
}

配置/ dev.env.js

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

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

配置/ 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根目录。

我们的webpack.base.conf.js看起来像这样。 建立/ 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看起来像这样

...
...
...
    "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的应用捆绑在一起,同时使用共享组件。

但是后来我们还有问题。如果你需要更多模块化的东西,我们就开始使用lerna。我建议你检查一下。

最好的问候。

答案 1 :(得分:8)

有一种简单的方法。在config/prod.env.js中附加您的变量:

module.exports = {
  NODE_ENV: '"production"',
  MY_URL: JSON.stringify(process.env.MY_URL || 'http://example.com')
}

然后按照以下方式运行您的构建:MY_URL=http://example.org npm run build

您的变量将在main.js中以process.env.MY_URL

的形式提供

答案 2 :(得分:0)

PROD:config/prod.env.js附加您的VAR='"value"'

'use strict'
module.exports = {
  NODE_ENV: '"production"',
  API_URL: '"https://production URL"'
}

DEV:config/dev.env.js附加您的VAR='"value"'

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_URL: '"http://localhost"'
})

您的变量将以process.env.API_URLprocess.env.VAR_NAME

的形式提供