Cannot find module "fs" - at webpackMissingModule - node.js

My server starts and runs correctly, but when I hit the URL in the browser it gives an error "cannot find module 'fs'".
I tried to setting:
target: 'node', but it starts another error
node: { fs: 'empty' }, but then it gives an error "cannot find exports"
"use strict";
const webpack = require('webpack');
const argv = require('minimist')(process.argv.slice(2));
const DEBUG = !argv.release;
const path = require('path');
var plugins = [
new webpack.optimize.CommonsChunkPlugin({
names: ['common', 'vendors'],
filename: '[name].js',
minChunks: Infinity
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': DEBUG ? '"development"' : '"production"',
"process.argv.verbose": !!DEBUG
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
jquery: "jquery"
})
].concat(DEBUG ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: true
}
}),
new webpack.optimize.AggressiveMergingPlugin()
]);
module.exports = {
entry: {
app: path.join(__dirname, '..', 'app', 'app.js'),
vendors: [
'react',
'react-dom',
'react-bootstrap',
'react-router',
'alt',
'lodash',
'superagent',
'react-router-role-authorization',
'react-validation-decorator'
]
},
output: {
publicPath: '/js/',
path: './wwwroot/js/',
filename: '[name].js',
chunkFilename: "[id].[name].js"
},
context: path.join(__dirname, '..'),
plugins: plugins,
cache: DEBUG,
debug: DEBUG,
watch: DEBUG,
stats: {
colors: true
},
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.json']
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader']
},
{
test: /\.(less|css)$/,
loaders: ["style", "css", "less"]
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.(eot|ttf|wav|mp3|mp4)$/,
loader: 'file-loader'
},
{
test: /\.json$/,
loader: 'json-loader'
}
]
},
node: {
net: 'mock',
dns: 'mock'
}
};
It should not give this error and work correctly.

I don't see any mention of the fs module in your posted webpack setup. So, my guess is that your output application (app.js?) is trying to require and use fs. Webpack is building a client-side, front-end application, one that will be loaded in the browser; fs is not available in the browser.
(Double-check and make sure you aren't trying to, for example, read and write files on the user's machine using fs inside your client-side application. That is not possible in a browser-based application. For an intro to the concept of web applications with a front end and back end, check out the article React App With Node Backend.)

Related

asset_url_for() returns None in flask cookie cutter (flask-webpack)

Im new to webpack. Im using flask-cookie-cutter which in turn uses Flask-Webpack
Im having issues in that App wont find my images in development.
Images are in assets/img folder
Ive tried using {{ asset_url_for('img/img_name.png') }} and various variations of it - and it just returns none.
Ive tried the usual flask way of {{ url_for('static', filename='img/img_name.png') }}
But I cant seem to access them.
const path = require('path');
const webpack = require('webpack');
/*
* Webpack Plugins
*/
const ManifestRevisionPlugin = require('manifest-revision-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// take debug mode from the environment
const debug = (process.env.NODE_ENV !== 'production');
// Development asset host (webpack dev server)
const publicHost = debug ? 'http://0.0.0.0:2992' : '';
const rootAssetPath = path.join(__dirname, 'assets');
module.exports = {
// configuration
context: __dirname,
entry: {
main_js: './assets/js/main',
main_css: [
path.join(__dirname, 'node_modules', 'materialize-css', 'dist', 'css', 'materialize.css'),
path.join(__dirname, 'assets', 'css', 'style.css'),
],
},
output: {
path: path.join(__dirname, 'dsi_website', 'static', 'build'),
publicPath: `${publicHost}/static/build/`,
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].js',
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
},
devtool: 'source-map',
devServer: {
headers: { 'Access-Control-Allow-Origin': '*' },
},
module: {
rules: [
{
test: /\.less$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader!less-loader',
],
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
},
},
'css-loader',
],
},
{
test: /\.html$/,
loader: 'raw-loader'
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff'
}
},
{
test: /\.(ttf|eot|svg|png|jpe?g|gif|ico)(\?.*)?$/i,
loader: `file-loader?context=${rootAssetPath}&name=[path][name].[hash].[ext]`
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['env'],
cacheDirectory: true
}
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: '[name].[hash].css', }),
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
new ManifestRevisionPlugin(path.join(__dirname, 'dsi_website', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
}),
].concat(debug ? [] : [
// production webpack plugins go here
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
}
}),
]),
};
I was the same problem with flask-cookie-cutter and solve it by update/upgrade npm and add extensionsRegex: /\.(jpe?g|png|gif|svg)$/i at down file: webpack.config.js like this:
ManifestRevisionPlugin(path.join(__dirname, '<your app>', 'webpack', 'manifest.json'), {
rootAssetPath,
ignorePaths: ['/js', '/css'],
extensionsRegex: /\.(jpe?g|png|gif|svg)$/i
}),
source solution. Proper call to show image in temaplate:
{{ asset_url_for('img/img_name.png') }}
after that i check startup screen and i see that all my images load properly
[WEBPACK] _/assets/img/image_name.20aed528d50316c91ffedb5ba47b8c74.jpg 18.9 KiB [emitted]

How to use webpack to create a front end and a admin?

I am actually new on node.js. I am trying to create an app with admin and frontend using webpack and express. I have created an example app but now the problem is how I can create the app with the admin. Below I have shared my webpack config file
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
frontend: './src/index',
backend: './admin/index'
},
module: {
loaders: [
{
test: /\.js?$/, loader: 'babel', exclude: /node_modules/
},
{
test: /\.css$/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
]
}
]
},
resolve: {
extensions: ['', '.js']
},
output: {
path: path.join(__dirname, '/public'),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './public',
hot: true
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
Webpack production configuration file
var config = require('./webpack.config.js');
var webpack = require('webpack');
config.plugins.push(
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": JSON.stringify("production")
}
})
);
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
);
Is there any easy solution or what I can do now?

How to configure webpack for nodejs with server side rendering

I'm trying to setup Webpack to generate 2 bundles, one for server code with server side rendering and one for client code. So far the bundle seems to generate correctly but when I run the server code and it tries to render some of my React components it throws errors like this one:
ERROR in ./~/react-load-script/lib/index.js
Module build failed: ReferenceError: Unknown plugin "add-module-exports" specified in "/Users/alex/Development/muub/one/website/node_modules/react-load-script/.babelrc" at 0, attempted to resolve relative to "/Users/alex/Development/muub/one/website/node_modules/react-load-script"
at /Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:180:17
at Array.map (native)
at Function.normalisePlugins (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
at OptionManager.mergeOptions (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
at OptionManager.init (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
at File.initOptions (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/index.js:212:65)
at new File (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/file/index.js:135:24)
at Pipeline.transform (/Users/alex/Development/muub/one/website/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
at transpile (/Users/alex/Development/muub/one/website/node_modules/babel-loader/lib/index.js:46:20)
at Object.module.exports (/Users/alex/Development/muub/one/website/node_modules/babel-loader/lib/index.js:163:20)
# ./App/Containers/Publish/Payment/Payment.jsx 18:0-39
# ./App/Containers/Publish/Payment/index.js
# ./App/Containers/Publish/Publish.jsx
# ./App/Containers/Publish/index.js
# ./App/Routes/index.js
# ./App/Containers/App.jsx
# ./App/index.js
# multi webpack-hot-middleware/client react-hot-loader/patch ./App
There are more errors similar to this one but related with other 3rd party npm packages.
Here is my webpack server config:
const path = require('path');
const webpack = require('webpack');
const ExternalsPlugin = require('webpack2-externals-plugin');
let conf = {
devtool: 'source-map',
context: path.resolve(__dirname),
entry: [
path.resolve(__dirname, 'index.js')
],
target: 'node',
output: {
path: path.join(__dirname, 'build'),
pathinfo: true,
filename: 'server.js',
publicPath: '/public/',
libraryTarget: 'commonjs2'
},
resolve: {
modules: ['App', 'node_modules'],
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: 'css-loader/locals',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]__[local]__[hash:base64:5]'
}
},
'postcss-loader'
]
},
{
test: /\.(js|jsx)?$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.HotModuleReplacementPlugin(),
new ExternalsPlugin({
type: 'commonjs2',
include: path.join(__dirname, 'node_modules'),
exclude: [path.join(__dirname, 'node_modules', 'webpack/buildin'), path.join(__dirname, 'App')]
}),
new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
]
}
module.exports = conf;
What could I be doing wrong?

TypeScript typings broken (error TS2687): All declarations of 'iterator' must have identical modifiers

I'm having an issue getting my typings correctly after I've added the router package to my Angular application (which required an upgrade of Core, Common, Compiler etc.).
Googling ob that specific error code led me to a number of problems, the main resolution for which is removing node_modules and typings and recreating them. I've done so but experience the same misbehavior.
On SO, there's another question but it's old, relates to a different versions of most of the packages and I hardly see how it relates to my problem.
Frankly, I'm a bit lost because I have no idea how to troubleshoot it at all. Below is my tsconfig.json if it helps to spot something odd.
edit
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const distribution = path.resolve(__dirname, "distribution");
const application = path.resolve(__dirname, "source/application");
const resources = path.resolve(__dirname, "source/resources");
module.exports = {
entry: "./source/application/main.ts",
output: {
path: distribution,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.png$/, loader: "raw-loader", include: [resources] },
{ test: /\.s(a|c)ss$/, loaders: ["raw-loader", "sass-loader"] },
{ test: /\.html$/, loader: "raw-loader", include: [application] },
{ test: /\.ts$/, loader: "ts-loader", include: [application] },
]
},
resolve: {
modules: ["node_modules", application],
extensions: [".js", ".ts"]
},
performance: {},
devtool: "source-map",
context: __dirname,
target: "web",
externals: [],
stats: {},
devServer: {
contentBase: distribution,
port: 3002
},
plugins: [
new HtmlWebpackPlugin({ template: "./source/index.html" }),
new CopyWebpackPlugin([{ from: "./source/resources", to: "resources" }])
]
}
In Webpack.common.js remove the line debug=true, and change the below code
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['*', '.js', '.ts']
},
module: {
rules: [
]},
plugins: [
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),

karma Uncaught SyntaxError: Unexpected token export

I use karma + jasmine to write test cases for vue and webpack, and it once worked. But after I upgrade vue for 1 to 2, and update vue-loader accordingly, it starts to give error.
Now when I run karma start karma.config.js, it give me error like:
Chrome 53.0.2785 (Windows 7 0.0.0) ERROR
Uncaught SyntaxError: Unexpected token export
at test/index.js:8995
My karma.config.js is:
var webpackConf = require('./webpack.config.js')
delete webpackConf.entry
module.exports = function (config) {
config.set({
browsers: ['Chrome'],
frameworks: ['jasmine'],
reporters: ['progress', 'html'],
htmlReporter: {
outputFile: 'tests/unit-test.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'A sample project description',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
// this is the entry file for all our tests.
files: [
{pattern: './test/index.js', watched: false},
],
// we will pass the entry file to webpack for bundling.
preprocessors: {
'./test/index.js': ['webpack']
},
// use the webpack config
webpack: webpackConf,
// avoid walls of useless text
webpackMiddleware: {
noInfo: true
},
singleRun: true,
plugins: [
'karma-chrome-launcher',
'karma-jasmine',
'karma-webpack',
'karma-htmlfile-reporter'
]
})
}
My webpack.config.js is:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: ['webpack-hot-middleware/client','./index.js'],
output: {
path: path.resolve(__dirname, '../output/static'),
publicPath: '/',
//filename: '[name].[hash].js'
filename: 'main.js'
//chunkFilename: '[id].[chunkhash].js'
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.common.js'
},
extensions: ['', '.js', '.vue']
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel?presets=es2015',
exclude: /node_modules/
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}
]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'index.html'),
inject: true
})
]
}
Looks like the es6 export syntax is not translated correctly. Also, I did not know where to take a look at the test/index.js:8995 because this is auto generated by webpack. The real index.js is quite simple, just 2 lines:
var testsContext = require.context('.', true, /\.spec\.js$/)
testsContext.keys().forEach(testsContext)
How to debug this and what can I do to solve the problem?

Resources