2017-08-13 114 views
0

我有一張使用本地json文件的d3.js從終端加載本地json數據到d3.js和webpack

爲了使數據可視化,我必須使用網絡服務器,所以我決定使用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" 

回答

0

那麼你可以使用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); 

Ca LL npm run special --myVar="special.js"

的結果應該是:

special.js 
+0

我可以用這與故宮?因爲我需要npm for webpack –