3

We are using the original Vuepress (0.x branch) and we want to use the configureWebpack method of the Vuepress config file to export some custom variables.

This code breaks the build, since Webpack doesn't allow custom properties since 2.0:

configureWebpack: (config) => {
  config.env = process.env
}

Error:

WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. - configuration has an unknown property 'env'.

I also looked at the Webpack docs for defining plugins however the problem is that the configureWebpack method doesn't actually expose the webpack instance Vuepress uses - it directly attempts to mutate the webpack options (which isn't allowed) - but as the webpack instance isn't available we can't simply define a plugin the way webpack wants us to.

Does anyone know the proper way to expose, say, configurable environment variables which we can use in our Vue components using Vuepress 0.x?

GrayedFox
  • 2,350
  • 26
  • 44

1 Answers1

9

Well... it took some arguing with the build pipeline of VuePress and jumping through Webpack fire hoops, but as VuePress uses Webpack, we can simply require it inside our config file (I assumed the method needed to expose VuePress's instance of Webpack, which is not correct).

If using dotenv, you can make custom environment variables available to your components this works:

// .vuepress/config.js
require('dotenv').config()
const webpack = require('webpack')

module.exports = {
  configureWebpack: (config) => {
    return { plugins: [
      new webpack.EnvironmentPlugin({ ...process.env })
    ]}
  }
}

Note: this would take everything from your env file and make it available inside all components, for production builds take only the keys you need.

GrayedFox
  • 2,350
  • 26
  • 44
  • I am doing this, but I still get `process is not defined` in the browser. What could I be doing wrong? – mspoulsen Sep 14 '20 at 09:37
  • this is super helpful, note that if you're using a custom env file (not `.env`) then you can set that in the `.config()` call, e.g. `require('dotenv').config({ path: '/custom/path/to/.env' })`, and if you want the import of that env file to override any existing env vars, you need to also add the `override` option: `require('dotenv').config({ override: true, path: '/custom/path/to/.env' })` ([see src](https://github.com/motdotla/dotenv#options)) – fredrivett Feb 15 '22 at 14:10