Try   HackMD

Using npm package in basic HTML

and also some get arounds to pass arrays from PHP to Javascript.

<script>
    const array_js = <?= json_encode($php_array) ?>;
</script>

okay that was a random bit that I'm just very excited to have found on the internet, I digress.

source: https://medium.com/hackernoon/use-es6-javascript-syntax-require-import-etc-in-your-front-end-project-5eefcef745c2

Motive

I'd preface this by saying my programming knowledge is pretty limited and if you think what I am going to do next is dumb or old, feel free to correct me, thanks.

So I wanted to use some npm packages (namely A-Frame and it's components), but since my company uses traditional-styled PHP, I had problems just say import package from "package" or something like that. Therefore we would need some other way to use npm pacakges. I am not sure how other packages, say React, would react (ba dumb tsz) but for my limited usage the source placed up top seems to work.

However there are some revisions I would like to point out because the authors methods didn't work for me.

Method

First create two files

  • index.html
  • node_packages/index.js

Go into the node_package/ (or whatever you want to name it) directory and npm init and install some packages

cd node_packages
npm init
npm i browserify watchify --save
npm i @babel/core @babel/preset-env babelify --save-dev
# the author used some older version packages

Go into your packages.json file and add the following lines

{
  ...
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "browserify index.js -o dist/bundle.js",
    "watch": "watchify index.js -o dist/bundle.js -v"
  },
  "browserify": {
    "transform": [
      [
        "babelify",
        {
          "presets": [
            "@babel/preset-env"
          ]
        }
      ]
    ]
  },
  ...
}

import pacakge from "package" in the index.js file. Run npm run build and then attach the Javascript file onto index.html with <script src="node_packages/dist/bundle.js"> and you could use npm pacakges in basic HTML.

If you'd like to fully follow along here's the full test code I have.
https://gitlab.com/imfulee/es6-html-demo