Custom global process.env variable with Webpack build - npm

I have a Vue application that's compiled using Webpack. I'm trying to add a variable into the 'npm run dev' command that I can then use globally throughout the project. Currently, I am running 'npm --brand=foo run dev' and consoling 'process.env.brand' in the build.js file returns 'foo'. Now I need to make this available to the rest of the project. Here is my setup:
WEBPACK.DEV.CONF.JS
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
module.exports = merge(baseWebpackConfig, {
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
})
})
DEV.ENV.JS
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
File structure is Build/build.js + webpack.dev.conf.js and Config/dev.env.js. I tried to add a 'brand' property like the following, but process.env.brand was undefined in this file.
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
brand: process.env.brand
})

UPDATE by #Linx to pass the argument dynamically directly from
command line
Run the command and pass in the variable like: npm --brand=foo run dev
Then, variable is then available in the webpack config file as
process.env.npm_config_brand.
Another option is to setting the variable inside the npm script section:
package.json
{
//...
"scripts": {
"dev": "SET brand=foo& webpack -p"
},
If you are using linux, maybe you should remove the SET --> "dev": "brand=foo& webpack -p"
Then run the command like: npm run dev
In both cases, to make it available for the rest of the project you can use webpack.DefinePlugin
module.exports = {
//...
plugins: [
new webpack.DefinePlugin({
'__BRAND__': process.env.brand,
})
]
}
The variable will be accessible in the rest of the project like: console.log(__BRAND__);

Related

process is not defined in Vue.js

I tried to use the process.env.process.env.VUE_APP_SERVER_URL in my vue project. But I got the error like the following.
Uncaught ReferenceError: process is not defined
It's using the webpack and run by npm start command.
Once you know the solution, please feel free to contact me.
You can add the following code in webpack.config.js.
const webpack = require('webpack');
const dotenv = require('dotenv').config({ path: __dirname + '/.env' })
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
'process.env': JSON.stringify(dotenv.parsed),
}),
]
...
}

Publish Vue using Development/Test config

I've looked and tried tons of different commands to get this to work, and nothing seems to do the trick.
I'm trying to get this setup so I can use a pipeline in Azure for a specific environment using settings in the environment specific config.
I've using vue cli 4.4.4. My Layout looks like this :
I've tried
vue build --mode development
vue-cli-service build --mode development
npm run build --development
npm run build -- --mode development
If they end up working, all they do is build in production anyway..
I'm running out commands. I would like it to use the dev.env.js config, it works fine in development when I use:
npm run dev
I've figured it out somewhat.
I can run :
npm run build --mode development
I had to modify the build.js and webpack.prod.config.js files to below:
build.js (grab the command 'development' from process.argv[2])
process.env.NODE_ENV = 'production';
var webconfigEnv = "production"
switch (process.argv[2] || 'production') {
case "development":
webconfigEnv = "dev"
break;
case "test":
webconfigEnv = "dev"
default:
break;
}
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for '+ webconfigEnv +'...')
spinner.start()
webpack.prod.conf.js (switch which config it is using from env in process.argv[2])
var webconfigEnv = "prod"
switch (process.argv[2] || 'production') {
case "development":
webconfigEnv = "dev"
break;
case "test":
webconfigEnv = "dev"
default:
break;
}
const env = require('../config/'+webconfigEnv+'.env')
console.log('Using config -- ../config/'+webconfigEnv+'.env');

Giving static filenames for build files in vue-cli3

I am using vue-cli3, when i build using npm run build -- --mode=production, it gives 2 css files and 2 js files.
Everytime i make a code change the name of the file also changes like app.de90cdf7.js and chunk-vendors.a9204242.js.
Is there a way in vue-cli to hardcode the files names as app.js and chunk-vendors.js ?
I'm little late to the party. We can chain webpack to apply name changes.
Using version #vue/cli 5.0.4 in year 2022
const { defineConfig } = require("#vue/cli-service");
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack : (config) => {
config.output.filename('[name].js');
},
css: {
extract: {
filename: '[name].css',
chunkFilename: '[name].css'
}
}
});

Adding pug-plain-loader configuration in vue.config.js

I have a project created through Vue CLI and now I want to use Pug with my Single File Components i.e. the .vue files.
To do that I started following this vue-loader documentation and installed pug and pug-plain-loader with the command npm install -D pug pug-plain-loader. And the next step there proposes inserting the follows in webpack.config.js
// webpack.config.js -> module.rules
{
test: /\.pug$/,
loader: 'pug-plain-loader'
}
But, using Vue CLI, I do not have an explicit webpack config file, but vue.config.js.
So, how to add such a pug-plain-loader configuration in vue.config.js (preferably using webpack-chain)?
My current vue.config.js already featuring a svg-loader is as follows:
module.exports = {
// ...
chainWebpack: (config) => {
const svgRule = config.module.rule('svg')
svgRule.uses.clear()
svgRule
.use('vue-svg-loader')
.loader('vue-svg-loader')
//TODO: add pug-plain-loader configuration here
}
}
Accordingly with the example here, Vue CLI has it own way to define new rules in webpack. So this code seems to be the right way to define the pug loader (in your vue.config.js file - if doesn't exists, create it):
module.exports = {
chainWebpack: (config) => {
// Pug Loader
config.module
.rule('pug')
.test(/\.pug$/)
.use('pug-plain-loader')
.loader('pug-plain-loader')
.end();
},
};
This worked for me c:
(this apply only in .vue files that have lang="pug" specified in template tag)

How to configure Production build and Development Build vue-cli

I want to setup a npm script for production build and one for development build. like npm run build for production and npm run buildDev for development.
I have some configurations in each env file like:
ROOT_API: '"url for the production"' and something else in the development env.
The build will be added to the dist folder.
I want the Production Build to be added to the dist folder and the Development Build to be added to a distDev folder.
I have tried to make a copy of the build.js file but without luck.
config/index.js:
'use strict'
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
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'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// 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
}
}
config/prod.env.js
module.exports = {
NODE_ENV: '"production"',
ROOT_API: '"url for production"'
}
config/dev.env.js
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
ROOT_API: '"url for development"'
})
build/build.js
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot,
config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP
server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
Any suggestions?
Didn't you try to use vue.config.js file to configure Vue build behavior?
You could specify an outputDir according to process.env.NODE_ENV at vue.config.js.
All environment-specific parameters would be set at .env.development and .env.production files accordingly.
Of course you can modify Webpack config through vue.config.js if you need, examples here.
Output directory parameter changing example is here.
At the end, your configuration file will depend only on environment variables and maybe some logic, e.g.:
module.exports = {
NODE_ENV: process.env.NODE_ENV,
ROOT_API: process.env.VUE_APP_ROOT_API_URL,
ANY_PARAM: process.env.VUE_APP_ANY_DOT_ENV_PARAM,
}
But remember, that your custom .env params should start with VUE_APP_ prefix, if you use them at templates.
Add --mode development entry in your package.json file like this: