Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  151] [ 3]  / answers: 1 / hits: 5768  / 2 Years ago, sat, october 22, 2022, 12:00:00

Hi i'm building an app using express and node. When I compile my project with webpack either in prod or dev mode I get the error : "Uncaught Error: Module parse failed: Unexpected token (8:20). You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file."


Now I don't know what type of file needs the loaders so I can't figure out what kind of loader I need to install in webpack. I've been trying to search here and done some googling but to no avail. If you can help me out with this I'd be really grateful!


My server.js:


const dotenv = require('dotenv');
dotenv.config();
function MeaningCloud(obj) {
return obj;
}
var textapi = new MeaningCloud({
application_key: process.env.API_KEY
});
projectData = {};

// Setup empty JS object to act as endpoint for all routes
projectData = {};

// Require Express to run server and routes
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

// Start up an instance of app
const app = express();

/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors for cross origin allowance
app.use(cors())
// Initialize the main project folder
app.use(express.static('client'));

app.get("/all", function sendData(req, res) {
res.send(projectData);
})

app.post("/add", (req, res) => {
projectData['lat'] = req.body.lat;
projectData['lng'] = req.body.lng;
projectData['countryCode'] = req.body.countryCode;
projectData['image'] = req.body.image;
res.send(projectData);
})

app.get("/", (req, res) => {
res.sendFile("index.html", { root: "src/client/views" })
})

// Setup Server
app.listen(3000, () => {
console.log("Listening on port 3000")
console.log("Go to http://localhost:3000")
})

My index.js:


const geoURL = "http://api.geonames.org/searchJSON?";
const geoUsername = `${process.env.GEO_USERNAME}`;
const weatherKey = `${process.env.WEATHER_KEY}`;
const weatherURL = "https://api.weatherbit.io/v2.0/current?";
const pixabayKey = `${process.env.PIXABAY_KEY}`;
const pixabayURL = "https://pixabay.com/api/?";

import getCity from getCity;
import getWeather from getWeather;
import getImage from getImage;
import postData from postData;
import receiveData from receiveData;

let d = new Date();
let newDate = d.getMonth() + 1 + "." + d.getDate() + "." + d.getFullYear();

const submitBtn = document.getElementById("submitBtn");

submitBtn.addEventListener("click", (e) => {
const city = document.getElementById("city");

if (city !== "") {
getCity(geoURL, city, geoUsername)
.then(city => getImage(pixabayURL, city, pixabayKey))
.then(cityData => getWeather(weatherKey, weatherURL, cityData))
.then(function (data) {
postData("/add", { lat: data.lat, lng: data.lng, countryCode: data.countryCode, image: data.image })
}).then(function () {
receiveData()
}).catch(function (error) {
console.log(error);
alert("Invalid city");
})
}
})

The error occurs at line 8 of the above file


so my getCity.js:


const getCity = async (geoURL, city, geoUsername) => {
const res = await fetch(`${geoURL}q=${city}&username=${geoUsername}`);
try {
const cityData = await res.json();
return cityData;
}
catch (error) {
console.log("error", error);
}
}

module.exports(getCity)

Also my webpack.config.js file! Sorry about that before!


const path = require('path')
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
entry: './src/client/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name][contenthash].js',
clean: true,
},
mode: 'development',
devtool: 'source-map',
stats: 'verbose',
module: {
rules: [
{
test: '/.js$/',
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/client/views/index.html",
filename: "./index.html",
}),
new CleanWebpackPlugin({
// Simulate the removal of files
dry: true,
// Write Logs to Console
verbose: true,
// Automatically remove all unused webpack assets on rebuild
cleanStaleWebpackAssets: true,
protectWebpackAssets: false
})
]
}

Update: So I thought it was something to do with images. So I updated the config.js to include that loader. But it still gives me the same error on the same line.


More From » node.js

 Answers
7

Change the module rule test for babel-loader to a Regular Expression instead of a String.


    module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},


Also, include quotes around the module name after from and move the import statements to the top of the file:


// For example
import getCity from "getCity";

[#21] Friday, July 29, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alanisannettep

Total Points: 695
Total Questions: 96
Total Answers: 91

Location: Australia
Member since Sat, May 27, 2023
1 Year ago
alanisannettep questions
Tue, Jun 22, 21, 00:00, 3 Years ago
Thu, Jul 30, 20, 00:00, 4 Years ago
Mon, Mar 16, 20, 00:00, 4 Years ago
Wed, Apr 24, 19, 00:00, 5 Years ago
;