I have a requirement in which I am rendering view in which I display a form. On submit of form i need to gather the form data and create a file and save form data as JSON in that file. I am using React.js, node.js, babel and webpack.
After struggling a bit to achieve this I figured out that I have to use isomorphic or universal javascript i.e use react and render on server side as we cannot use fs module on client side. Referred this for server side.
i run it using: npm run start
After this I can see in console that [Object Object]
is printed on console from Line 1 in below react component (HomePage.js). But later on when I access this page it gives an error:
'bundle.js:18 Uncaught Error: Cannot find module "fs"'
How can i use fs module with react ?
Below are code snippets :
webpack.config.js
"use strict";
const debug = process.env.NODE_ENV !== "production";
const webpack = require('webpack');
const path = require('path');
module.exports = {
devtool: debug ? 'inline-sourcemap' : null,
entry: path.join(__dirname, 'src', 'app-client.js'),
devServer: {
inline: true,
port: 3333,
contentBase: "src/static/",
historyApiFallback: true
},
output: {
path: path.join(__dirname, 'src', 'static', 'js'),
publicPath: "/js/",
filename: 'bundle.js'
},
module: {
loaders: [{
test: path.join(__dirname, 'src'),
loader: ['babel-loader'],
query: {
//cacheDirectory: 'babel_cache',
presets: debug ? ['react', 'es2015', 'react-hmre'] : ['react', 'es2015']
}
}]
},
plugins: debug ? [] : [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
mangle: true,
sourcemap: false,
beautify: false,
dead_code: true
}),
]
};
See Question&Answers more detail:os