我想使用NodeJS默认fs模块读取和写入文件。 我几乎尝试了我能在互联网上找到的一切。 ES6和CommonJS示例,编辑Webpack.config文件,添加应该添加Promises的包等等。但似乎没有任何结果。
目前这是我的webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: './index.js',
output: {
path: 'public',
filename: 'bundle.js',
publicPath: ''
},
node: {
fs: "empty"
},
"browser": { "fs": false },
resolve: {
modulesDirectories: ['web_modules', 'bower_components', 'node_modules']
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader?presets[]=es2015&presets[]=react'
}
]
}
}
正如我已经提到添加了一些行suggested in this topic。
我想在下面显示的组件中使用fs.readFile
:
var React = require('react');
var fs = require('fs');
var QuestionList = React.createClass({
handleVote: function(id, state) {
var file = '../public/api/questions';
fs.readSyncFile(file, function(err, data) {
console.log( err );
console.log( data );
});
},
render() {
var rows = []
this.state.questions.forEach( function(question) {
rows.push(
<QuestionItem
onVoteUpdate={this.handleVote}
key={question.id}
up={question.upvotes} down={question.downvotes}
/>
);
}.bind(this));
return (
<section>
<ul className="question-list">{rows}</ul>
</section>
)
}
});
module.exports = QuestionList;
我删除了一些函数,例如使用jQuery加载问题并为此示例设置InitialState
。
我可以想象webpack不能在前端js文件或类似之类的东西中构建任何后端任务,但是怎样才能读取和使用Node,Webpack和React写文件?这甚至可能吗?
答案 0 :(得分:1)
据我所知,您不能在前端JS文件中使用fs
,因为您无法从浏览器访问文件系统(看起来您可能期望{ {1}}调用在Webpack的编译过程中运行 - 这不是它的工作原理!)。您需要某种Webpack加载器来创建它,以便您可以readFileSync
该文件,或者您必须通过AJAX加载它。