【问题标题】:Load local json data from terminal to d3.js and webpack将本地 json 数据从终端加载到 d3.js 和 webpack
【发布时间】:2018-01-21 12:42:33
【问题描述】:

我有一个使用本地 json 文件的 d3.js 制作的图表。

为了可视化数据,我必须使用网络服务器,所以我决定使用 webpack,因为它还提供热重载。

问题是我仅限于所选文件 (data.json),因为它是出现在入口点 (index.js) 中的文件:

index.js

d3.json("data.json", function(error, d) {
    // get data and draw chart

当我想显示图表时,我使用npm start 并转到localhost:8080

package.json

{
  "name": "tutorial",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server",
    "build": "babel src -d lib",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-preset-env": "^1.3.3",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.28.0",
    "style-loader": "^0.16.1"
  }
}

webpack.config.js

const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: './src/index.html',
  filename: 'index.html',
  inject: 'body'
})
module.exports = { 
  entry: './src/index.js', 
  output: { 
    path: path.resolve('dist'), 
    filename: 'index_bundle.js'
  }, 
  module: { 
    loaders: [ 
      { test: /\.js$/, 
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      { test:/\.css$/,
        loader: ['style-loader', 'css-loader'],
        exclude: /node_modules/
      },
    ]
  }, 
  plugins: [
    HtmlWebpackPluginConfig,
    new CopyWebpackPlugin([
      { from: 'src/data.json'}
    ])
    ]
}

如何将 json 文件作为参数传递?类似:

npm start "another_data.json"

还是使用节点?

node "another_data.json"

【问题讨论】:

    标签: javascript json node.js d3.js


    【解决方案1】:

    你可以使用 process.argv,它是包含所有命令行参数的数组。 你可以试试:

    process.argv.forEach(function (item, index) {
      console.log(index + ': ' + val);
    });
    

    所以如果你打电话给node app.js "ok" "non",你会得到类似的东西:

    0: /usr/src/node/node-v4.4.7-linux-x64/bin/node
    1: /home/scrapbook/tutorial/app.js
    2: ok
    3: non
    

    或者使用 npm:

    {
      "name": "adsf",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "special": "node app.js"
      },
      "author": "",
      "license": "ISC"
    }
    

    使用 app.js:

    console.log(process.env.npm_config_myVar);
    

    致电npm run special --myVar="special.js"

    结果应该是:

    special.js
    

    【讨论】:

    • 我可以将它与 npm 一起使用吗?因为我需要用于 webpack 的 npm
    猜你喜欢
    • 2013-03-03
    • 2018-10-10
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2012-09-13
    • 2015-10-23
    • 2013-03-23
    相关资源
    最近更新 更多