简体   繁体   中英

How to make my npm typescript module usable in simple Javascript project?

I recently create a module to listen keypressed input on document to get events from physical barcode reader used as keyboard.
The source can be found here : https://github.com/tii-bruno/physical-barcode-reader-observer
The npm module here : https://www.npmjs.com/package/physical-barcode-reader-observer
I had no problem to use it on an Ionic project (Angular + Cordova).
But I would like to use it on a simple PHP / Javascript project (wich does not use npm but old include script), and I have some difficulties to do that …
I tried to browserify with gulp but when I tried to use my class, I have an error like MyObject is undefined …
Could you, please, tell me how I can achieve my goal?

You will need to make a "build pipeline". Definitely the best way to manage npm packages is thought npm , so your project should include a package.json along the other project files.

In this "build pipeline", in order to build your whole project (idk if you are using Makefile or another building tool) first you need to build the client (the javascript). You must have a main.js file in order to start bundling your app. This file will look like this:

const pbro = require('physical-barcode-reader-observer');
const anotherModule = require('./local_module.js');
...

As you can see, inside this main file we require all the modules we want, so any bundle tool (such as Browserify, or webpack) knows which file is the entry point of the application. For example, browserify docs sais:

browserify main.js -o bundle.js

Then you will have all modules bundled to one single file, in this case bundle.js .

Next, we would like to include this bundle to our html file like this:

<html>
    <body>
        <script src="bundle.js" />
    </body>
</html>

Note: this is just a suggestion, there are many ways to include the bundled file automatically into the html like with webpack and it's html-webpack-plugin

What we got so far is just the "build pipeline", what is needed to do next is to plan the deploy. For this you will need to set up a webserver and configure it in order to serve the bundled file. For example, if your domain is www.domain.com, then you will have to set the webserver up in order to find www.domain.com/bundle.js (as stated in the html file).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM