Vue.js, global variables and TypeScript

It’s pretty easy to pass some environment variable to Vue.js application using webpack.DefinePlugin. You just need to have something like a sample below in your webpack.config.js:

var webpack = require('webpack')

module.exports = {
 // ...
 plugins: [
   // ...
   new webpack.DefinePlugin({
     'BUILD': JSON.stringify(0.0.1')
   })
 ]
}

It’s a common way to pass some environment variable into your JavaScript application. Technically, webpack.DefinePlugin injects a global variable into your JavaScript application. You may need it for some feature flags or some global configuration.

Do not forget to use JSON.stringify because of DefinePlugin inserts raw string and it could lead to some unexpected results.

It works pretty well until you need all these things with TypeScript. First of all, you need to change your vue.conf.js to add metiond webpack plugin:

configureWebpack: {
    plugins: [
      new webpack.DefinePlugin({
           'BUILD': JSON.stringify(0.0.1')
    }),
    ]

After that, you need to define a global variable BUILD somewhere in your TypeScript code: declare var BUILD: string;. It’s required because TypeScript doesn’t know anything about global JavaScript variables, so you need to declare them.

I did it in the globals.ts:

declare var BUILD: string;

export default BUILD;

So I can use it everywhere in a project: import BUILD from '@/globals.ts';.

The same procedure should be followed if you want to access environment variables from your code (actually, webpack will inject variables values into the code, because I don’t have access to them from the browser). In the JavaScript world, you can just use process.env.BASE_URL and everything will work. But for TypeScript you have to declare a new global variable:

    env: {
        BUILD: string
    }
}```


Nothing unexpected happened, you just need to remember that every variable you can easily use in JavaScript you have to declare in TypeScript. It’s just because TypeScript is a strong-typed programming language. These actions could be obvious you anybody who knows TypeScript well, but it leads to difficulty for newbies.

Tags

.net .net-framework .net-framework-3.5 agile ajax ajax-control-toolkit ampq ansible apache asp.net asp.net-mvc automation axum babel bash benchmark blog blog-engine bootstrap buildout c# cache centos chrome ci cinder ckan cli cloud code-review codeplex community config debugger deface dependencies development-environment devices devstack devtime disks django dlr dns docker dockerimage dos easy_install elmah encoding environment-variables error event events everything-as-a-code exception exceptions fabrik firefox flask foreach forms fstab gae gcc gerrit git github go google google-app-engine grep hack hacked hardware headless horizon hound html hugo iaas ienumerable iis internet iptables iron-python ironic iscsi java-script javascript jenkins jquery js jsx k8s kharkivpy kiss kombu kubernetes kvm kyiv lettuce libvirt linux lio loci logging loopback losetup lvm mac-os macos mercurial microsoft microsoft-sync-framework mobile mono ms-office msbuild networking news nginx npm npx offtopic oop open-source open-xml opensource openstack openvswitch os packages paraller-development patterns-practices performance php pika pip plugins pnp podcast popup postgresql profiler project protocols proxy pycamp pycharm pycon pykyiv pylint pypi python python-3 qcow quantum qumy rabbitmq rar react reactjs refactoring rfc rhel search-engine security selenium server shell silverlight socket software-engineering source-control sourcegear-vault sources sql sql-server sql-server-express sqlalchemy ssh static-site sublimetext svg tests tgt tipfy todo tornado typescript uapycon ui uneta unit-tests upgrades usability vim virtualenv visual-studio vitrage vm vue.js vuejs web-development web-server web-service web_root webpack webroot windows windows-live word-press x32 x64 xcode xml xss xvfb интернет-магазин книги

Recent posts

Go 1.18: new features

Всё будет Kubernetes

2022 Relaunch

Everyday Blogging

I don't want this CI


Archives

2022 (3)
2019 (73)
2018 (2)
2017 (3)
2016 (2)
2015 (3)
2014 (5)
2013 (17)
2012 (22)
2011 (36)
2010 (25)
2009 (35)
2008 (32)
2007 (2)