thewhitefox

theWhiteFox design & build web apps

thewhitefox

webpack Fetch API

2021 January 1st

Why Webpack Fetch?

Learning the basics of JavaScript Fetch API & webpack. Fetch an interface JS makes it simpler, cleaner & more logical API requests, using promises.

Yeah let's code!

Create a basic fetch function called fetchText, using async await. readme is a local text file.

1async function fetchText() {
2 let response = await fetch('./readme.txt');
3 let data = await response.text();
4 console.log('fetchText: ' + data)
5}
6
7fetchText();
8
9async function fetchText2() {
10 let response = await fetch('./non-existence.txt');
11
12 console.log(response.status); // 404
13 console.log(response.statusText); // Not Found
14
15 if (response.status === 200) {
16 let data = response.text();
17 // handle data
18 console.log('fetchText2: ' + data)
19 }
20}
21
22fetchText2();

webpack

1const path = require('path');
2
3module.exports = {
4 entry: [
5 "@babel/polyfill",
6 './src/js/app.js',
7 './src/sass/app.scss'
8 ],
9 output: {
10 path: path.resolve(__dirname, 'dist/'),
11 filename: 'js/main.js'
12 },
13 module: {
14 rules: [
15 {
16 test: /\.m?js$/,
17 exclude: /(node_modules|bower_components)/,
18 use: {
19 loader: 'babel-loader',
20 options: {
21 presets: ['@babel/preset-env'],
22 plugins: ['@babel/plugin-proposal-object-rest-spread']
23 }
24 }
25 }, {
26 test: /\.scss$/,
27 exclude: /node_modules/,
28 use: [
29 {
30 loader: 'file-loader',
31 options: { outputPath: 'css/', name: '[name].min.css'}
32 },
33 'sass-loader'
34 ]
35 }
36 ]
37 },
38 devServer: {
39 contentBase: path.join(__dirname, './'),
40 compress: true,
41 port: 3000
42 }
43};

Tutorial

JavaScript Fetch API

theWhiteFox Fetch API Webpack Basics repo

Code BlocksJS Algorithms