Cannot read properties of undefined (reading 'match') at getLocalIdent - javascript

i'm trying to make build script. so i can build with webpack it kinda like this
build.server.js
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
process.on('unhandledRejection', err => {
throw err;
});
require('../config/env');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.server');
const paths = require('../config/paths');
function build() {
console.log('Creating server build');
fs.emptyDirSync(paths.ssrBuild);
let compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, status) => {
if (err) {
console.log(err);
return;
}
console.log(status.toString());
});
});
}
build();
after i code this and type node scripts/build.server.js , this error comes out.
Cannot read properties of undefined (reading 'match')
at getLocalIdent (C:\Users\jhs00\OneDrive\바탕 화면\공부자료\ssrProject\ssrproject\node_modules\react-dev-utils\getCSSModuleLocalIdent.js:20:49)
getLoslIdent is in here (webpack.config.server.js)
const nodeExternals = require('webpack-node-externals')
const webpack = require('webpack');
const paths = require('./paths');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
...
i searched similar question and tried delete package-lock.json, node_modules and reinstall it. but didn't work. what should i do?

Related

Listing all the declared slash command to a json file Discord js

I'm building a discord bot using discord.js. All of my source code is from the official discord.js guide website, and I'm wondering how I could list all declared slash commands to a JSON file commands.json.
Here is my code:
deploy_commands.js:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
const commands = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
index.js:
const { Client, Collection, Intents } = require("discord.js");
const client = new Client({intents: [Intents.FLAGS.GUILDS]});
const config = require("./config.json");
const { guildId, clientId, token } = require('./config.json');
const fs = require('node:fs');
const path = require('node:path');
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.commands.set(command.data.name, command);
}
client.once('ready', () => {
console.log(`user : ${client.user.tag}\nguildid : ${guildId}\nclientid : ${clientId}`);
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({content: 'Sorry, there was a problem while executing this command, maybe try again later?', ephemeral: true});
}
});
client.login(token);
deploy_commands.js is a file for deploying commands, and what I want to do is to save all the declared slash commands and transfer all of them to a JSON file.
I personally suggest you the usage of map() to manage the array where you store every command inside deploy_commands.js.
Following you can find a solution that worked for me:
const fs = require('fs');
const commands = [...commandBuilders...].map(command => command.toJSON());
const commandsToString = JSON.stringify(commands);
fs.writeFile('commands.json', commandsToString, (e, res) =>{
if (e) console.log('ERROR: ' + e);
}

How do you dynamically module.export all files in a folder?

I'm trying to dynamically export modules. I'm close but can't figure out how to fix my syntax.
Hard coded:
// index.js inside folder 'models'
const { User } = require('./User');
const { Token } = require('./Token');
const { Session } = require('./Session');
module.exports = {
User,
Token,
Session,
};
Dynamically coded (doesn't work):
// index.js inside folder 'models'
const fs = require('fs');
const path = require('path');
module.exports = () => {
fs.readdirSync(__dirname).forEach((file) => {
if (file === 'index.js') return false;
const fullName = path.join(__dirname, file);
if (file.toLowerCase().indexOf('.js')) {
// I think this somehow needs to be destructured like
// `return {require(fullName)}` or
// `require(fullName)[fullName]` I think
require(fullName);
}
});
};
Elsewhere in my code, I initialize it based on the folder name:
// server.js
require('./models')();
Your dynamic export will not work because you are not returning anything to the exported function.
Try this code as your dynamic model export file
// index.js inside folder 'models'
const fs = require('fs')
const path = require('path')
const models = {}
fs.readdirSync(__dirname)
.filter(file => file !== 'index.js')
.forEach(file => {
const fullName = path.join(__dirname, file)
if (file.toLowerCase().endsWith('.js')) {
// Removes '.js' from the property name in 'models' object
const [filename] = file.split('.')
models[filename] = require(fullName)[filename]
}
})
module.exports = models
This approach no longer exports a function so your require in server.js should now look like this
// server.js
require('./models');

Overwriting files in Node server

So I have a server that temporarily saved the files in it's memory, before I upload them to the database. Here's my code:
uploadImage(file, uid, res) {
var fs = require('fs');
mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));
var conn = mongoose.connection;
Grid.mongo = mongoose.mongo;
const gfs = Grid(conn.db);
const writeStream = gfs.createWriteStream({
filename: file.filename,
});
fs.createReadStream(file.path).pipe(writeStream);
writeStream.on('close', file => {
const {_id} = file;
return Account.findByIdAndUpdate(uid, {'employer.logo': _id}).then(() => res.redirect('/employer')).catch(e => console.log(e));
});
},
I am trying to optimize the images before uploading them to the database, like this:
async uploadImage(file, uid, res) {
const imagemin = require('imagemin');
const imageminJpegtran = require('imagemin-jpegtran');
const imageminPngquant = require('imagemin-pngquant');
console.log(1);
// const newFilePath = `${file.path}optimized`;
const newFile = await imagemin([file.path], file.path, {
plugins: [
imageminJpegtran(),
imageminPngquant({quality: '65-80'})
]
});
// newFile.path = newFilePath;
console.log(2);
console.log(file);
console.log(newFile);
var fs = require('fs');
await mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));
var conn = mongoose.connection;
Grid.mongo = mongoose.mongo;
const gfs = Grid(conn.db);
const writeStream = gfs.createWriteStream({
filename: newFile.filename,
});
fs.createReadStream(newFile.path).pipe(writeStream);
writeStream.on('close', file => {
const {_id} = file;
return Account.findByIdAndUpdate(uid, {'employer.logo': _id}).then(() => res.redirect('/employer')).catch(e => console.log(e));
});
},
But this tells me EEXIST: file already exists, mkdir '/home/alex/Documents/Projects/ontario-job-portal/public/images/logos/b80872b65d18d09bb498abcabe2f3f94', which is true. I'm trying to overwrite the previous image.
How can I make it overwrite the file though?
Creating a new file results in a permission denied error.
Edit. IMPORTANT
Turns out, that the object returned by the imagemin function is a little different from the previous one. Here's my working code:
async uploadImage(file, uid, res) {
const imagemin = require('imagemin');
const imageminJpegtran = require('imagemin-jpegtran');
const imageminPngquant = require('imagemin-pngquant');
console.log(1);
const path = require("path");
const newFilePath = path.dirname(file.path);
const newFile = await imagemin([file.path], path.dirname(file.path), {
plugins: [
imageminJpegtran(),
imageminPngquant({quality: '65-80'})
]
});
newFile.path = newFilePath;
newFile.filename = newFile[0].path.replace(/public\/images\/logos\//, '');
console.log(newFile.filename);
var fs = require('fs');
await mongoose.connect(config.db, {useNewUrlParser: true},).catch(e => console.log(e));
var conn = mongoose.connection;
Grid.mongo = mongoose.mongo;
const gfs = Grid(conn.db);
console.log(2);
const writeStream = gfs.createWriteStream({
filename: newFile[0].filename,
});
console.log(3);
fs.createReadStream(newFile[0].path).pipe(writeStream);
console.log(4);
writeStream.on('close', file => {
console.log(5);
const {_id} = file;
return Account.findByIdAndUpdate(uid, {'employer.logo': _id}).then(() => res.redirect('/employer')).catch(e => console.log(e));
});
},
It looks like you are providing the path of an existing file to imagemin where a directory is required. To extract the directory from the path, use path.dirname(file.path):
const path = require("path");
const newFile = await imagemin([file.path], path.dirname(file.path), {
...
Note that this won't overwrite the existing file. It doesn't appear that imagemin supports that directly. You could do it yourself manually using fs if you wanted, but I'm not sure why you would. It seems like you are interested in using these as temporary files. You may want to add some code to delete the files after they have been written to mongo.

module.exports function is not a function

I'm trying to require an endpoints.js file into my webpack.config.js
Expected
endpoints.js gets required correctly then sets a custom api file depending on the process.env.NODE_ENV
Results
const api = endpoints(process.env.NODE_ENV);
TypeError: endpoints is not a function
Webpack.config.js
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const endpoints = require("./src/endpoints");
const api = endpoints(process.env.NODE_ENV);
console.log('webpack endpoints', endpoints);
console.log('webpack api', api);
endpoints.js
module.exports = {
endpoints: function(env) {
let prefix = env === 'development' ? 'http://localhost' : '';
return {
"login": `${prefix}/app/api/login`
}
}
}
I also tried the following, but got an Unexpected token export
export default function endpoints(env) {
let prefix = env === 'development' ? 'http://localhost' : '';
return {
"login": `${prefix}/app/api/login`
}
};
Ah I was using module.exports wrong, however it looked correct according to this site.
This is how I needed to use module.exports to export out my endpoints function.
function endpoints(env) {
let prefix = env === 'development' ? 'http://localhost' : '';
return {
"login": `${prefix}/app/api/login`
}
}
module.exports = endpoints;

How to create/generate/export a file from my webpack 2 config to be used inside of my React code?

I am passing in NODE_ENV variables into my webpack.config from package.json in order to return an object that either contains API endpoints for localhost or production.
1) package.json
"scripts": {
"dev": "NODE_ENV=development webpack-dev-server --history-api-fallback",
"prod": "NODE_ENV=production webpack -p",
"build": "NODE_ENV=production webpack -p"
}
2) endpoints.js
function endpoints(env) {
let prefix = env === 'development' ? 'http://localhost' : '';
return {
"login": `${prefix}/app/api/login`
}
}
module.exports = endpoints;
3) webpack.config
const webpack = require('webpack')
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const dist = path.resolve(__dirname, "dist");
const src = path.resolve(__dirname, "src");
const endpoints = require("./src/endpoints");
const api = endpoints(process.env.NODE_ENV);
console.log('webpack api', api);
module.exports = {
context: src,
entry: [
"./index.js"
],
output: {
path: dist,
// ....
Here below I can see the console.log of the const api.
Now my question is, how do I now generate or export out an actual file api to be used inside of my src/services/api file:
import axios from 'axios'
// import api from '../../webpack.config' <-- ?
// import api from '../../api.js <-- ?
const log = (method, err) => {
console.error(`%c${method}`, 'background: #393939; color: #F25A43', err);
return null;
};
export const userLogin = (username, password) => {
const post_data = { username, password };
return axios.post('http://localhost/app/api/login', post_data) // <-- api to be used here
.then(res => res)
.catch((err) => log('api.userLogin', err));
};
I think this is an XY problem. You could generate the files with a bit of Node (something like fs.writeFileSync('api.js', contents), or you could do it with a bit of shell scripting, but you could also just use env in your code using DefinePlugin (example: new webpack.DefinePlugin({ env: JSON.stringify(process.env.NODE_ENV) }). Then you'd be able to access env in your code directly.

Categories

Resources