简体   繁体   中英

How to require additional modules in node.js app

Hei, I'm trying to get a tablesorter for my app. I wanted to go with this one ( https://github.com/tristen/tablesort ) but I have problems with getting it to work. I have it in my package.json file and I install it throughout NPM and later require it in code like var tablesort = require('tablesort'); . The main problem is with modules that come with it. In github project they are required like this: <script src='tablesort.number.js'></script> . How can I transform that kind of code to node/require friendly code which will load all those modules and let me sort my tables? I have no idea how to get this tablesorter running with nodejs app.

Since you use Browserify , you should be allright.

The TableSort library has a CommonJS compatible export in its source code. Adding

var TableSort = require("tablesort");

to your source code should be sufficient to include the library into your built bundle, as well as provide you a reference to the TableSort constructor. The project's README even has that example .

However, the same is not true for the bundled sort-methods, as they expect to find a global reference to the TableSort prototype, which they then extend using its extend method, eg TableSort.date .

You can Browserify-shim to make CommonJS incompatible modules CommonJS compatible. However, in my quick experiments, I couldn't get it working properly without some slicing and dicing. For some reason browserify-shim's file resolution failed when including a file in a subfolder of a package.

I did manage to include the sort-methods by copying them into my project folder. I made a Gist demo of including one shimmed sort-method. Clone it, run npm install && npm run build , then open index.html in your browser.

You can download the tablesort.js from here to your directory, and then add this to the file:

  module.exports =  Tablesort;

Then, if you want a spesific tablesort, for example "number". you should download tablesort.number.js from here

Then, you should add this changes to tablesort.number.js

    var Tablesort= require('./tablesort.js')

    module.exports =  Tablesort;

Finaly, in your file you use this:

var tablesort = require('./tablesort.number.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