簡體   English   中英

需要來自node.js模塊的“所有內容”

[英]Require “everything” from a node.js module

我正在寫一個DSL,我想把所有模塊中的所有內容放到當前的命名空間中,以便能夠編寫這樣的東西

// I know it's not working.
// In python, I'd do: from mydsl import *
{*} = require('./mydsl');

node('London');
node('Paris');
edge('London', 'Paris');

以下是我嘗試作為解決方法的一些版本

// In python: import mydsl as dsl
dsl = require('./mydsl');
dsl.node('London');

// In python: from mydsl import node, edge
{node, edge} = require('./mydsl');
node('London');

// Extend `this` with imported functions
_ = require('underscore');
_.extend(this, require('./mydsl'));
this.node('London');

由於我的DSL有很多關鍵字,使用{node,edge,...} = require會很笨拙。 我更喜歡可以使用browserify移植到網絡上的解決方案。

這是一個非常非常糟糕的做法。

_ = require('underscore');
_.extend(global, require('./mydsl'));
node('London');

你有沒有考慮使用with

var mydsl = require('./mydsl');
with (mydsl) {
    node('London');
    node('Paris');
    edge('London', 'Paris');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM