在webpack中动态添加全局常量

时间:2018-05-23 20:21:25

标签: javascript typescript webpack vue.js

我试图为我的项目添加一个全局常量。为此我使用webpack.DefinePlugin。如果我在module.exports中添加一个,这是有效的。但是我没有条件地这样做。在下面的配置中,我可以在声明之后在我的模块中使用__VERSION__常量:declare var __VERSION__: string;。如果我尝试使用__VERSION2____VERSION3__,我会在控制台ReferenceError: __VERSION3__ is not defined中收到错误消息。如果我的理解是正确的,那么应该更换。这是否意味着条件部分未执行或未正确执行?我该怎么调试呢?或者甚至更好,我该如何解决这个问题?

注意:目的是根据开发或生产构建来切换URL。

可以找到当前项目here on github

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())
        }));
}

1 个答案:

答案 0 :(得分:0)

经过大量的搜索和调整,我发现问题根本与webpack无关。感谢this article我在if / else if前面添加了console.log(process.env.NODE_ENV);,并在undefined之后添加了 "scripts": { "build": "SET NODE_ENV=development&& webpack", "test": "echo \"Error: no test specified\" && exit 1" }, 。未设置环境变量,因此不会执行任何条件语句。这实际上是vue.js打字稿模板的一个问题。

更改package.json中的脚本就像修复了我的问题:

@Component
public class Example {

    private LocalDate localDate;

    @Value("${property.name}")
    private void setLocalDate(String localDateStr) {
        if (localDateStr != null && !localDateStr.isEmpty()) {
            localDate = LocalDate.parse(localDateStr);
        }
    }
}