Categories
JavaScript Answers

How to load fonts with Webpack and font-face with JavaScript?

To load fonts with Webpack and font-face with JavaScript, we set the modules property to load the fonts.

For instance, we write

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpackConfig = require("./webpack.config");

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.(sa|sc|c)ss$/,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
      {
        test: /\.(png|woff|woff2|eot|ttf|svg)$/,
        use: ["url-loader?limit=100000"],
      },
    ],
  },
};

to set the module.rules property to load woff, woff2, eot, and ttf fonts.

And we set it to use url-loader to load the font files.

Categories
JavaScript Answers

How to fix webpack-dev-server Cannot find module ‘webpack’ error with JavaScript?

To fix webpack-dev-server Cannot find module ‘webpack’ error with JavaScript, we install some missing packages.

To install it, we run

npm install --save-dev webpack-dev-server 

to install webpack-dev-server to let us import the package.

Categories
JavaScript Answers

How to resolve Node Socket.io 404 (Not Found) error?

To resolve Node Socket.io 404 (Not Found) error, we connect to the URL and port of the Socket.io server.

For instance, we write

const app = express();
const server = app.listen(3000);
const io = require("socket.io").listen(server);

to call app.listen` to listen to port 3000.

Then we call listen with server to add socket.io to our app.

We can then connect to it at the URL with port 3000.

Categories
JavaScript Answers

How to fix AWS missing credentials when trying send something to S3 Bucket in Node.js?

To fix AWS missing credentials when trying send something to S3 Bucket in Node.js, we call the config.update method.

For instance, we write

AWS.config.update({
  accessKeyId: "YOURKEY",
  secretAccessKey: "YOURSECRET",
  region: "sa-east-1",
});

const s3 = new AWS.S3();
const params = {
  Bucket: "makersquest",
  Key: "mykey.txt",
  Body: "HelloWorld",
};
s3.putObject(params, (err, res) => {
  if (err) {
    console.log("Error uploading data: ", err);
  } else {
    console.log("Successfully uploaded data to myBucket/myKey");
  }
});

to call update to update access key and secret key to connect to AWS.

Categories
JavaScript Answers

How to loop through JSON with Node.js?

To loop through JSON with Node.js, we use the forEach method.

For instance, we write

const objectKeysArray = Object.keys(yourJsonObj);

objectKeysArray.forEach((objKey) => {
  const objValue = yourJsonObj[objKey];
});

to call Object.keys to get the object’s keys in an array.

Then we call forEach with a callback to get the property value with yourJsonObj[objKey].