GrayedFox
GrayedFox

Reputation: 2553

How do I expose Node environment variables via configureWebpack to Vuepress components?

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?

Upvotes: 3

Views: 2240

Answers (1)

GrayedFox
GrayedFox

Reputation: 2553

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.

Upvotes: 9

Related Questions