parcel: Cannot use functions in HTML from referenced script

πŸ› bug report

When attempting to use a function (in an onclick and onload, specifically) from an imported script in HTML (i.e <script src="test.js"></script>), I get ReferenceError: x is not defined for every function. This has been tested only when running locally in the default parcel dev mode.

πŸŽ› Configuration (.babelrc, package.json, cli command)

{
  "scripts": {
    "build": "parcel build src/index.html --detailed-report",
    "dev": "parcel src/index.html"
  },
  "dependencies": {},
  "devDependencies": {
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "parcel-bundler": "^1.9.2"
  },
  "babel": {
    "presets": [
      [
        "env",
        {
          "targets": {
            "browsers": [
              "last 3 versions",
              "not ie < 11"
            ]
          }
        }
      ]
    ],
    "plugins": [
      "transform-runtime"
    ],
    "comments": false
  },
  "browserlist": [
    "last 3 versions",
    "not ie < 11"
  ]
}

πŸ€” Expected Behavior

When I call a function in HTML that is defined in an imported file, I should run that function

😯 Current Behavior

Uncaught ReferenceError: login is not at HTMLButtonElement.onclick ((index):27)

πŸ’ Possible Solution

Not really sure. I’ve tried using export on my functions as well. Only directly inlining the script seems to work.

πŸ”¦ Context

I’d like to be able to define some simple JS functions in a separate file from my HTML. Currently, I’m building a static login page, but the login logic is complex enough that I’d like for it to live in a separate file.

πŸ’» Code Sample

https://github.com/JonathanTroyer/Parcel-html-import

🌍 Your Environment

Software Version(s)
Parcel 1.9.3
Node 8.11.1 OR 10.5.0
npm/Yarn 5.6.0/1.7.0
Operating System Windows 10 Pro Version 1803 Build 17134.112

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 1
  • Comments: 17 (3 by maintainers)

Most upvoted comments

Could you refer to this example: https://github.com/buronnie/parcel-global-var-test? The class name is sitting in the namespace of SpaceInvaders. Still not exactly what you want, but at least it is working πŸ˜„

@buronnie I tried your example, it works:

image

In my example, adding .ts seems to have fixed the initial issue:

image

I use postcss imports

Isn’t this already possible with β€”global <some variable name> ?

Sent with GitHawk