NodeJS how-to require module which injects a funct

2019-09-14 17:43发布

I am using webpack to bundle a visualisation built with d3 and a d3.slider module, yet this is a more general problem - how do I require() a module which patches a module (d3 here) with a function (here d3.slider()) ?

package.json:

{
  "name": "d3_slider_error",
  "version": "0.0.1",
  "description": "",
  "main": "",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack-dev-server"
  },
  "dependencies": {
    "d3": "^3.5.15",
    "d3-slider": "git+ssh://git@github.com:MasterMaps/d3-slider.git",
    "webpack": "^1.9.10",
    "webpack-dev-server": "^1.9.0",
    "html-webpack-plugin": "^1.5.0"
  }
}

webpack.config.js :

var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');

module.exports = {
    entry: "./src/main.js", // APP_PATH
    output: {
        filename: 'main.js',
        path: path.resolve('./dist') // BUILD_PATH  
    },
    module: {
        loaders: [
            //
        ]
    },
    resolve: {
        modulesDirectories: ['node_modules']
    },
    plugins: [
        new HtmlWebpackPlugin({title : "d3-slider-error"})
    ]
};

src/main.js:

var d3 = require('d3');
require('d3.slider');

var timeSlider = d3.slider();

console.log("Done!");

This logs: TypeError: d3.slider is not a function

1条回答
我想做一个坏孩纸
2楼-- · 2019-09-14 18:14

I found an ugly'ish solution, but since nothing else came up, I'm posting it here. I add this to package.json dependencies:

"script-loader": "git+ssh://git@github.com:webpack/script-loader.git"

Then somewhere, for example in the entry point (assuming that d3.slider is in node_modules):

require("script!d3.slider");

Script-loader executes the script in the global environment once. Should work for all similar problems, legacy scripts etc. Done.

查看更多
登录 后发表回答