I'm facing a challenge with adding a global constant to my project using webpack.DefinePlugin. I've successfully added one in the module.exports, but I struggle to do this conditionally. When I declare and use '__VERSION__' in my module as 'declare var __VERSION__: string;', it works fine. However, if I try to use '__VERSION2__' or '__VERSION3__', I encounter an error 'ReferenceError: __VERSION3__ is not defined'. I expected the conditional part to replace the constants. Does this mean the conditional part is not executed correctly? How can I debug this issue or better yet, how can I resolve it?
It's worth mentioning that the purpose is to switch a URL based on whether it's a development or production build.
You can access the current project here on GitHub
Here is the webpack.config.js:
// Based on https://github.com/microsoft/typescript-vue-starter#adding-webpack
var path = require('path')
var webpack = require('webpack')
module.exports = {
mode: 'development',
entry: './src/ts/main.ts',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax',
}
// other vue-loader options go here
}
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/],
}
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
resolve: {
extensions: ['.ts', '.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
plugins: [
new webpack.DefinePlugin({
__VERSION__: JSON.stringify('1.0.0.' + Date.now())
})],
devServer: {
historyApiFallback: true,
noInfo: true
},
performance: {
hints: false
},
devtool: 'source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = 'source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.DefinePlugin({
__IN_DEBUG__: JSON.stringify(false),
__VERSION2__: JSON.stringify('1.0.0.' + Date.now())
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
else if(process.env.NODE_ENV === 'development')
{
module.exports.plugins.push(
new webpack.DefinePlugin({
__VERSION3__: JSON.stringify('1.0.0.' + Date.now())
}));
}