I, am trying to use the fs module but I get this error
Module not found: Error: Can't resolve 'fs' in '/home/pau/Escritorio/Master/Blockchain/Prac2/PRAC2_Template/Ejercicio_2/app/src'
# ./src/index.js 5:11-24
I have fs installed and for what I've seen, theres a problem with webpack that makes this happen.
Mi packeage.json is this
{
"name": "app",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"build": "webpack",
"dev": "webpack-dev-server"
},
"devDependencies": {
"copy-webpack-plugin": "^5.0.5",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
},
"dependencies": {
"fs": "0.0.1-security",
"ipfs-http-client": "^47.0.0",
"web3": "^1.8.1"
}
}
and my webpack.config.js this
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
},
plugins: [
new CopyWebpackPlugin([{ from: "./src/index.html", to: "index.html" }]),
],
devServer: { contentBase: path.join(__dirname, "dist"), compress: true },
};
I found this link https://github.com/webpack/webpack/issues/13498, where they say that adding
module: {
rules: [
{
test: /#aws-sdk\/lib-storage\//,
resolve: {
alias: {
'./runtimeConfig': './runtimeConfig.browser',
},
},
},
],
},
The problem disappear, but it doesnt work for me. My webpack.config.js with that code looks like this:
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
},
plugins: [
new CopyWebpackPlugin([{ from: "./src/index.html", to: "index.html" }]),
],
devServer: { contentBase: path.join(__dirname, "dist"), compress: true },
module: {
rules: [
{
test: /#aws-sdk\/lib-storage\//,
resolve: {
alias: {
'./runtimeConfig': './runtimeConfig.browser',
},
},
},
],
},
};
But I get the same error.
How can I solve this?
fs is a built-in module in Node.js. You just have to require it, like this:
const fs = require('fs');
and then you can use it.
The fact, that you have fs in your package.json might interfere with the built-in module. You should remove fs from your package.json and run npm install to remove any packages, which might have been unnecessarily installed.
After that it should work.
Related
I have a webpack project 3 and I want to run it on my local system.
Here is my webpack config file and the package.json
{
"private": true,
"name": "XXx",
"version": "Xxx",
"description": "X",
"main": "index.js",
"dependencies": {
"babel": "^6.23.0",
"css-loader": "^0.28.8",
"extract-text-webpack-plugin": "^3.0.2",
"findandreplacedomtext": "^0.4.6",
"raw-loader": "^0.5.1",
"style-loader": "^0.19.1",
"text-loader": "0.0.1"
},
"devDependencies": {
"nodemon": "^1.19.4",
"sass": "^1.58.0",
"uglifyjs-webpack-plugin": "^1.1.6",
"webpack": "^3.10.0"
},
"scripts": {
"min.js": "make min.js",
"min.css": "make min.css",
"serve": "webpack"
},
"author": "",
"license": "ISC"
}
Makefile
const UglifyJs = require('uglifyjs-webpack-plugin')
const isWatching = process.argv[2] === '-w'
const plugins = [
function() {
this.plugin('watch-run', function(watching, callback) {
console.log('Begin compile at ' + new Date())
callback()
})
}
]
if (!isWatching) {
plugins.unshift(
new UglifyJs({
extractComments: false,
sourceMap: true,
})
)
}
module.exports = {
entry: {
'bundle': './js/bundle.js'
},
devtool: isWatching ? 'source-map' : false,
output: {
path: `${__dirname}/js`,
filename: '[name].min.js',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.html$/,
use: {
loader: 'raw-loader',
}
},
{
test: /\.s?css$/,
use: [
{
loader: "css-loader",
options: {
url: false, // do not bundle images
},
},
{loader: "sass-loader"},
],
}
]
},
plugins,
}
There is a makefile but I dont think this is required for this problem.
I have tried
webpack -p , webpack -w , and webpack .
webpack -p is giving an error : ERROR in bundle.min.js from UglifyJs Unexpected token: punc ({) [bundle.min.js:1,976]
while webpack -w works fine I am unable to find any url for the website.
the last command runs and ends.
I am using webpack 5 with typescript and a node.js app.
My folder structure is
src/
server.ts
mymodule.ts
public/
index.html
main.ts
utils.ts
but I want to output the compiled files as
dist/
server.js
mymodule.js
public/
index.html
bundle.js
This is my package.json
{
"name": "to-do",
"version": "1.0.0",
"description": "An application for to do list",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node server.js",
"debug": "node --inspect server.js",
"build": "webpack",
"serve": "webpack serve"
},
"license": "MIT",
"dependencies": {
"express": "^4.18.1",
"filenamify": "^5.1.1",
"html-webpack-plugin": "^5.5.0",
"http": "^0.0.1-security",
"ts-loader": "^9.3.1",
"typescript": "^4.7.4",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.3"
},
"keywords": [
"todo"
],
"devDependencies": {
"#types/express": "^4.17.13",
"#types/node": "^18.0.6"
}
}
This is my webpack configuration
import path from 'path';
import { fileURLToPath } from 'url';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default {
entry: {
bundle : './src/public/main.ts'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
target:'node',
resolve: {
extensions: ['.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/public/index.html',
scriptLoading:"module"
})
],
output: {
filename: '[name].js',
path: path.join(__dirname, 'dist'),
clean: true
},
mode: 'development',
devtool: 'inline-source-map',
devServer: {
hot: true,
static: {
directory: './dist',
},
compress: true,
port: 3002,
headers: {
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin'
}
},
stats: {
errorDetails:true
}
};
I get an error about server.js can't be resolved, since I assume it looks at the main from package.json.
ERROR in ./src/public/main.ts 3:0-36
Module not found: Error: Can't resolve './server.js' in 'C:\Users\Desktop\4\src\public'
resolve './server.js' in 'C:\Users\Desktop\4\src\public'
using description file: C:\Users\Desktop\4\package.json (relative path: ./src/public)
using description file: C:\Users\Desktop\4\package.json (relative path: ./src/public/server.js)
no extension
How can I resolve this?
I am working with a Raspberry Pi Zero that is my server, running my module.
Raspberry's are not the best to compile code so I want to compile the server-side code locally. To do so I need to compile the code without resolving my imports. Why that ?
Because the Server module uses other modules that can only be installed on the Raspberry (such as UPM or MRAA for sensors).
For now I compile on the Pi but it's slow.
So I'm trying to compile to ES6 locally with my config:
const path = require("path");
const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");
module.exports = {
entry:
{
index: __dirname + "/src/index.js"
},
output: {
// sourceMapFilename: "[name].map",
path: path.resolve(__dirname, "build"),
filename: "[name].js",
sourceMapFilename: "[name].map",
chunkFilename: "[id].chunk.js"
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
cacheDirectory: true,
presets: ["env"],
plugins: [
["transform-runtime"],
["transform-es2015-modules-commonjs-simple", { // Very important
"noMangle": true
}]
]
}
}
}
]
},
plugins: [
new webpack.ProvidePlugin({Hardlets: path.resolve(__dirname, "../Hardlets/build/index")}),
new webpack.IgnorePlugin(new RegExp("/(node_modules)/"))
// new webpack.optimize.UglifyJsPlugin(),
// new HtmlWebpackPlugin({template: "./src/index.html"})
],
target: "node",
externals: [nodeExternals()],
devtool: "source-map"
};
Which gives me an error because only the devDependencies are installed locally but not the other dependencies (sensors...):
ERROR in ./src/hardlets/relays/Relays.js Module not found: Error:
Can't resolve 'jsupm_relay' in
'/home/stinky/Projects/gardener/Sensors/src/hardlets/relays' #
./src/hardlets/relays/Relays.js 1:1008-1030 #
./src/HardletInstances.js # ./src/index.js
ERROR in ./src/hardlets/dht22/DHT22.js Module not found: Error: Can't
resolve 'rpi-dht-sensor' in
'/home/stinky/Projects/gardener/Sensors/src/hardlets/dht22' #
./src/hardlets/dht22/DHT22.js 1:925-950 # ./src/HardletInstances.js
# ./src/index.js
How can I prevent webpack from trying to resolve/import these dependencies ? The dependencies must be resolved at runtime.
There is my package.json:
{
"name": "gardener",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack --watch",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "http://192.168.8.100:3000/pi/Gardener.git"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-runtime": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-plugin-transform-es2015-modules-commonjs-simple": "^6.7.4",
"webpack": "^3.8.1",
"webpack-node-externals": "^1.6.0"
},
"dependencies": {
"upm": "^1.0.0",
"rpio": "^0.9.19",
"rpi-dht-sensor": "^0.1.1"
}
}
The modules could not be excluded with nodeExternals() because it lists the modules in /node_modules/. However, the modules that are to be excluded are not installed locally so nodeExternals() does not do the job.
It needs to exclude them from by reading package.json.
This will read the modules from the package.json file & exclude them instead of the node_modules directory:
// webpack.config.js
var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
externals: [nodeExternals({
modulesFromFile: true
})], // in order to ignore all modules in package.json when bundling
...
};
I have a problem when I can use mongoose with webpack. I already installed it as a dependency but when I want to use the mongoose object and execute it it commands me that it can not find the "." Module. And that seems very strange, I've been looking for a good time, I installed the dependencies again, delete the npm cache, reinstall webpack
I would appreciate your support, thank you very much
webpack.config.js
var path = require("path");
var typescriptLoader = {
test: /\.ts$/,
loader: 'ts-loader'
};
module.exports = {
entry: "./src/main.ts",
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
publicPath: "dist/",
filename: "main.js"
},
node: {
__filename: true,
__dirname: true
},
watch: true,
devServer: {
contentBase: path.join(__dirname, "public_html"),
watchContentBase: true
},
module: {
rules: [ typescriptLoader ]
},
resolve: {
extensions: [ '.js', '.ts' ]
},
externals: {
}
}
package.json
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack --config webpack.config.js -p",
"start": "node dist/main.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"karma": "^1.5.0",
"ts-loader": "^2.0.1",
"typescript": "^2.2.1",
"webpack": "^2.2.1"
},
"dependencies": {
"#types/core-js": "^0.9.39",
"#types/helmet": "0.0.34",
"#types/mongoose": "^4.7.10",
"#types/node": "^7.0.11",
"body-parser": "^1.17.1",
"cheerio": "^0.22.0",
"express": "^4.15.2",
"helmet": "^3.5.0",
"mongoose": "^4.9.4",
}
}
index.ts
import * as mongoose from 'mongoose'; // ALL OK
console.log(mongoose); // Error when is used
Error
var n;n="undefined"==typeof window?!function(){var e=new Error('Cannot find module "."');throw e.code="MODULE_NOT_FOUND",e}():r(204),/*!
^
Error: Cannot find module "."
Your mongoose is npm module. TypeScript may not recognized the way you import it. try the nodejs require module loading system.
var mongoose = require('mongoose');
or
const mongoose = require('mongoose');
I was planning to use ES6 Modules on front-end so I did experiment on Webpack. However, I am having a hard time making the ff: work
Hot reload when there are changes in client-side
Hot reload when there are changes in server-side (before webpack, I'm using nodemon . and not have issues with it)
Losing debug/console.log info in terminal since it's printing the webpack status and nothing on the server e.g my custom 'Server running....' log.
The setup below I was trying to run via npm start. And everytime I make any change, I have to run npm start again
package.json
{
"name": "socket-io-chat",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "npm run build",
"build": "webpack -d && webpack-dev-server --hot --inline --watch && node --watch",
"build:prod": "webpack -p && webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.7.1",
"express": "*",
"socket.io": "*"
},
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-stage-2": "^6.13.0",
"nodemon": "^1.10.2",
"webpack": "^1.13.2",
"webpack-dev-server": "^1.15.1"
}
}
webpack.config.js
var path = require("path");
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var SRC_DIR = path.join(__dirname, "public");
var DIST_DIR = path.join(__dirname, "public/js/dist");
var config = {
context: __dirname,
devtool: debug ? "inline-sourcemap" : null,
entry: {
guest : path.join(SRC_DIR, "entry-guest.js"),
authenticated : path.join(SRC_DIR, "entry-authenticated.js")
},
output: {
path: DIST_DIR,
filename: "[name].js"
},
modules: {
loaders: [
{
test: /\.js?/,
include: SRC_DIR,
loader: "babel-loader",
query: {
presets: ["es2015", "stage-2"]
}
}
]
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
devServer: {
https: false,
contentBase: SRC_DIR,
stats: 'errors-only',
port: 3000
}
};
module.exports = config;
server.js
//create server
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
console.log('here');
var server = require('http').createServer(app);
//prepare socket io, make it listen to server
var io = require('socket.io').listen(server);
users = [];
connections = [];
var port = process.env.PORT || 3000;
server.listen(port);
console.log(`Server running *:${port}`);
//routing
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
//open a connection
io.sockets.on('connection', function(socket) {
connections.push(socket);
console.log('Connected: %s sockets connected:', connections.length);
//...more codes here
});
In your webpack config file you can try using the plugin "Hot Module Replacement"
Along side with your already implemented Nodemon you should have both the client and server reloading on changes.
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
}
})
],
Here is an example webpack config utilizing HotModuleReplacement.
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3001',
'webpack/hot/only-dev-server',
path.resolve(__dirname, 'client', 'index.jsx')
],
output: {
path: path.resolve(__dirname, 'public'),
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
}
})
],
resolve: {
modules: [path.resolve(__dirname, 'node_modules')],
extensions: ['*', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
]
},
devServer: {
port: 3001,
contentBase: path.resolve(__dirname, 'public'),
hot: true,
historyApiFallback: true
},
devtool: 'source-map'
};