3

In my current project I have a lot of global variables: (not declared with var)

HELLO = 'Hello';

I installed babel so I can use all the ES next functions, but it seems babel doesn't now how to deal with global variables

.babelrc

{
  "presets": [
    [
    "@babel/preset-env",
    {
      "modules": "commonjs"
    }
  ]
  ],
  "plugins": ["angularjs-annotate"]
}

UPDATE!!

Seems that it comes from babel transpiling. Babel added: "use strict"; . That's why my code failed

IsraGab
  • 4,819
  • 3
  • 27
  • 46
  • 2
    I think it want you to declare them all in the global scope from the start of your file with a line like : `var HELLO, OTHER_GLOBAL, AND_A_THIRD_ONE` – jonatjano Jan 13 '19 at 10:33
  • I can't do it right now. My project is huge and I don't know where are all the global variables – IsraGab Jan 13 '19 at 10:34
  • What is the exact and complete error message you are getting? – str Jan 13 '19 at 10:34
  • ReferenceError: `variable` is not defined (Where variable is the variable name) – IsraGab Jan 13 '19 at 10:35
  • You still should declare global variables with `var`, otherwise that assignment *is* an error in strict mode. – Bergi Jan 13 '19 at 14:17
  • How did you configure your babel? Did it enable strict mode or modules? – Bergi Jan 13 '19 at 14:18
  • @Bergi I edited my question. When I remove the commonjs, It works but I need it for another loader – IsraGab Jan 13 '19 at 15:47

2 Answers2

1

Ok. It takes me a while to figure it out.

here's the solution: Add that to the plugins in .babelrc

"plugins": [
    ["@babel/plugin-transform-modules-commonjs", {
    "strictMode": false
  }],
      "angularjs-annotate"
  ]
IsraGab
  • 4,819
  • 3
  • 27
  • 46
  • 1
    While this technically works, this is not the recommended approach. The duplicate should explain better. Use [`sourceType`](https://babeljs.io/docs/en/options#sourcetype) – loganfsmyth Jan 13 '19 at 21:39
0

you can achieve global by assign var to the window like so:

window.HELLO = 'hello';
l1nuxuser
  • 315
  • 4
  • 11