简体   繁体   中英

client-side node module doesn't work after browserify

I'm trying to develop an app under node.js. I need a module named autocomplete so I did

npm install -S autocomplete

and that worked fine. packages.json was updated and everything.

But I need the functionality of autocomplete on the client side. The most popular solution to this problem seems to be to use browserify, so I installed that globally and it seems to work.

Now according to everything I've read, I should be able to:

cd node_modules
browserify autocomplete/index.js > bundle.js
mv bundle.js ../public/lib/js/

and then in views/index.html I should be able to have

<script src="lib/js/bundle.js">

and finally I should be able to say

var auto = new Autocomplete();

because the Autocomplete object is defined in the autocomplete module and that's how the instructions say to instantiate it.

But unfortunately my browser says Autocomplete is not defined so it's clearly not getting the message.

What is wrong with the above?

When you run Browserify, create it as a standalone module:

browserify autocomplete/index.js --standalone Autocomplete > autocomplete.js

I'm only changing the name here for simplicity - call it whatever you want.

Then, when you run this in the browser as you have it currently, new Autocomplete() should be available.

Edit While this is doable, the docs for this module are missing, and the module you are reading the docs for seems missing.

There isn't a need to go to this trouble when you can use something like typeahead which is already built for the browser.

So it turns out because Autocomplete is not exported to the global scope. Try this in the file where you use Autocomplete, for example in the app.js:

var Autocomplete = require('autocomplete');
var auto = new Autocomplete();

Then

browserify app.js > bundle.js
mv bundle.js ../public/lib/js/

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