我有一个使用本地json文件的 d3.js 制作的图表。
为了可视化数据,我必须使用Web服务器,所以我决定使用 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 :(得分: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);
致电npm run special --myVar="special.js"
结果应该是:
special.js