V
V
Vitaly Makeev2014-04-13 11:21:50
Node.js
Vitaly Makeev, 2014-04-13 11:21:50

How to replace a module when building a JavaScript package?

There is a certain library, in the code of which the logger module is requested :

// Исходный не собранный в пакет код, может выполнятся без сбоки в node.js
var logger = require('../../tools/logger');
module.exports = { 
    // ...
};
The implementation of the logger module is environment dependent, so if building for the browser, a different logger module is used .
In other words , the assembly should return a module . I can't figure out how to replace one module with another, provided that the module is requested by a relative path (both modules are outside the node_modules folder ). PS I'm trying to use Browserify to create an assembly .
require('../../src/logger');
'../../src/logger/browser'


Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Makeev, 2016-10-01
@wmakeev

Now for these purposes I use a folder node_modulesinside the project.
For example:

src/node_modules/_project/logger/index.js
src/node_modules/_project/logger/browser/index.js

In code:
When running a project in node, it defaults to _project/logger/index.js.
If you need a browser version, the module can be easily replaced during the build process (for example, using webpack).
  • It's a hack
  • Need to explicitly include the folder src/node_modulesin .gitignore
    node_modules
    !src/node_modules

  • You need to configure the code editor or IDE so that the built-in search and auto-completion tools consider the nested node_modules not as a folder with external modules

T
Timur Shemsedinov, 2014-04-16
@MarcusAurelius

You need the "interface" pettern, i.e. the same appearance of the logger and different implementation, loaded depending on the platform. Look here the interface is implemented through impurities: habrahabr.ru/post/183188 Here is the library itself with examples https://github.com/tshemsedinov/global.js And a live example of using this method can be found here https://github.com/ tshemsedinov/impress /lib/ directory has impress.security.js and impress.security.mongodb.js is its implementation or db.js is interface and its implementations are db.mysql.js, db.mongodb. js, db.memcached.js. In the latter case (with the db interface), they not only implement the interface, but also extend it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question