ReferenceError after using Webpack? [duplicate] - javascript

Here is my webpack.config.js
module.exports = {
entry: "./src/index.js",//path relative to this file
output: {
filename: "../frontEnd/bundle.js",//path relative to this file
},
externals: {
puppeteer: 'require("puppeteer")',
},
mode: 'development'
}
Here is the file, index.js, where the webpack is ran:
var backendScript = require('../backEnd/backend');
var safeBackendScript = require('../backEnd/safeBackend');
function test(){
document.getElementById("Fname").value= "John"
document.getElementById("Lname").value= "Smith"
document.getElementById("Phone").value= "1234567890"
document.getElementById("Email").value= "Jsmith#domain.com"
document.getElementById("Saddress").value= "123 Main Street"
document.getElementById("Zip").value= "12345"
document.getElementById("country").value= "USA"
document.getElementById("state").value= "NJ"
document.getElementById("cardtype").value= "AE"
document.getElementById("Cname").value= "JOHN H SMTIH"
document.getElementById("Cnumber").value= "1234567890101112"
document.getElementById("CVV").value= "123"
document.getElementById("cardmonth").value= "01"
document.getElementById("cardyear").value= "2035"
document.getElementById("category").value= "jackets"
document.getElementById("kword").value= "Supreme Jacket"
document.getElementById("delay").value= "120"
document.getElementById("color").value= "C2"
document.getElementById("size").value= "L"
}
module.exports = {
test: test
}
And then here is my html with the function ran:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script type= "text/javascript" src="./bundle.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Supreme Bot</title>
</head>
<body style="margin: 20px">
<button onclick="test()"> test </button>
</body>
</html>
then after clicking on the button, it states that test() is undefined...
I can't figure it out...
Any help is GREATLY appreciated.

You aren't exporting test() to window.
module.exports = {...} won't automagically get injected into window, but:
you can set the output.libraryTarget: 'window' and output.library: 'something' configuration options and get window.something.test() (docs here), or
you can manually do window.test = test; at the end of your Webpack entry point instead of exporting things.

Related

Suddenly, my custom Github pages site redirect to Readme.md

Situation:
I've successfully published a custom domain site using Github pages. The URL is: https://stigmastories.com/
The site was working fine, until 2 days ago, I found out that people were being redirected to the Readme.md. I did not push any changes, so this was extremely odd. It just stopped working.
Setup details:
It's a simple create-react-app
My index.html is not in the root. It's in the public folder.
This is my directory structure:
- build
- node_modules
- public
- index.html
- 404.html
- manifest.json
- src
- package.json
- CNAME
- README.md
This is my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Fighting Stigma Through Art"
/>
<!-- Start Single Page Apps for GitHub Pages -->
<script type="text/javascript">
(function(l) {
if (l.search[1] === '/' ) {
var decoded = l.search.slice(1).split('&').map(function(s) {
return s.replace(/~and~/g, '&')
}).join('?');
window.history.replaceState(null, null,
l.pathname.slice(0, -1) + decoded + l.hash
);
}
}(window.location))
</script>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/favicon.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<script src="//embed.typeform.com/next/embed.js"></script>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=FOO"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('FOO');
</script>
<title>Stigma Stories</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root">
</div>
</body>
</html>
This is my manifest.json:
{
"short_name": "Stigma Stories",
"name": "Stigma Stories",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
This is my 404.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Single Page Apps for GitHub Pages</title>
<script type="text/javascript">
var pathSegmentsToKeep = 0;
var l = window.location;
var textFrag = performance.getEntriesByType("navigation")[0].name.split('stories')[2] || '';
l.replace(
l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
l.hash + textFrag
);
</script>
</head>
<body>
</body>
</html>
And in my package.json , I have a:
"homepage": "https://coreyarch4321.github.io",
I am deploying from my main branch from the root folder. My deploy script looks like:
"deploy": "gh-pages -d build",
Other important notes:
I've done my fair share of research on what could be wrong. I see people talk about how you should:
move index.html and all other files up to the root. I shouldn't need to do this. It was working fine before. I'd like to fix this without having to resort to that.
Any type of help would be appreciated. Let me know if you need any other info!

Why does embedding webpack into index.html gives me an unexpected token error?

I have tried to add Webpack to my vue project to use the require.context, but unfortunately it doesn't work.
When I run my project I get these errors:
Uncaught SyntaxError: Unexpected token '<'
and
Error in mounted hook:
TypeError: __webpack_require__(...).context is not a function
The "Unexpected token" error comes from embedding Wepback in index.html with the script tag. But when I delete it the error goes away.
Here's the code:
webpack.config.js
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
}
]
},
plugins: [
new VueLoaderPlugin()
]
};
index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<link rel="stylesheet" href="https://use.typekit.net/hcp1kvq.css">
<title><%= htmlWebpackPlugin.options.title %></title>
<base href="/" />
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<script src="../dist/main.js"></script>
</body>
</html>
Art.vue
<template>
<div>
<h1>Art</h1>
<ArtImage :key="key" v-for="(img, key) in images" :link="imageDir + key.substr(1)" />
<div :key="key" v-for="(img, key) in images" >
<img :src="imageDir + key.substr(1)" class="" >
</div>
</div>
</template>
<script>
import ArtImage from "../components/ArtImage.vue"
export default {
components: {
ArtImage,
},
data() {
return {
imageDir: "../assets", // you know this already just from directory structure
images: {}
}
},
mounted() {
this.importAll(require.context(this.imageDir, true, /\.png$/))
},
methods: {
importAll(r) {
var imgs = {}
r.keys().forEach(key => (imgs[key] = r(key)))
this.images = imgs
}
}
}
</script>
<style>
</style>

What is wrong with my Babel configuration?

I have configured Babel for my project with ".babelrc" file. My .babelrc file is,
{
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "entry"
}
]
]
}
I have imported "core-js/stable" and "regenerator-runtime/runtime" using index.js in my index.html as follows. I'm using Parcel as the packaging tool.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="../js/index.js"></script>
<title>Document</title>
</head>
<body>
<h1>Hello Second App</h1>
<script>
(() => {
console.log('welcome ...');
})();
function getUserById(id) {
return Promise.try(function () {
if (typeof id !== "number") {
throw new Error("id must be a number");
}
return "done";
});
}
getUserById();
</script>
</body>
</html>
Also as you can see I'm trying to use "Promise.try". But I'm getting
Promise.try is not a function
So why Babel is not fixing this? Please help me. I'm trying to understand Babel.

angular runtime, styles and polyfiles get a 404 error on my web server

I have made a little Angular application, I have built it on my computer, but when I try to open the index.html file I have 404 errors, I tried to deploy it on a web server but it's the same :
GET http://www.valhatech.com/runtime-es2015.edb2fcf2778e7bf1d426.js net::ERR_ABORTED 404 (Not Found)
GET http://www.valhatech.com/styles.365933d9cb35ac99c497.css net::ERR_ABORTED 404 (Not Found)
GET http://www.valhatech.com/polyfills-es2015.2987770fde9daa1d8a2e.js net::ERR_ABORTED 404 (Not Found)
My index.html file is that :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>McKenzieEquation</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="assets/js/app.js"></script>
</head>
<body>
<app-root></app-root>
</body>
</html>
And the content of my app.module.ts is :
const routes: Routes = [
{ path: 'home', component: AppComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', redirectTo: 'home' }
];
#NgModule({
declarations: [
AppComponent,
MckenzieGraphComponent
],
imports: [
BrowserModule,FormsModule,RouterModule.forRoot(routes, { useHash: true })
],
providers: [MckenzieEquationService],
bootstrap: [AppComponent]
})
export class AppModule { }
Firefox console send me on a Reason: CORS request not HTTP error or URI of module source is not authorized in this document : « file:///polyfills-es2015.2987770fde9daa1d8a2e.js ».
I have found my error. On my web server my angular page was located to the following path :
/www/mckenzieequation
And my index file was written like that :
<head>
<meta charset="utf-8">
<title>McKenzieEquation</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="assets/js/app.js"></script>
</head>
I have to replace the base parameter with the following code :
<base href="/mckenzieequation/">
The base href must pointing to the place of the index file.

Mochai Chai test not running

I'm learning app testing at the moment, using this course: https://code.tutsplus.com/courses/angularjs-for-test-driven-development/
I'm on lesson 2.3 where we have Mocha and Chai installed, a test folder with main.spec.js setup and gulp task setup to serve the app and tests.
When he updated his main.spec.js file with this simple describe statement:
describe('The Address Book App', function() {
it ('should work', function() {
chai.assert.isArray([]);
});
});
It ran fine for him:
However here is my setup:
test/main.spec.js
describe('The Dashboard app', function() {
it ('should work', function() {
chai.assert.isArray([]);
});
});
Basic markup:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mocha Spec Runner</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="icon" href="../app/favicon.ico">
<link rel="apple-touch-icon" href="../app/assets/imgs/apple-touch-icon.png">
<link href="testing.css" rel="stylesheet">
</head>
<body>
<div id="mocha"></div>
<script src="../bower_components/mocha/mocha.js"></script>
<script>
mocha.setup('bdd');
</script>
<script src="../bower_components/chai/chai.js"></script>
<script>
mocha.run();
</script>
<script src="main.spec.js"></script>
</body>
</html>
However my test file isn't displaying my first test:
Gulpfile setup, same as the authors, cept PORT numbers are different:
gulp.task('serve', function() {
browserSync.init({
notify : false,
port : 3333,
server: {
baseDir: ['app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
gulp.task('serve-test', function() {
browserSync.init({
notify : false,
port : 4444,
server: {
baseDir: ['test', 'app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
Any idea why my first basic test isn't running?
Everything looks right except the ordering.
Just swap the
<script>
mocha.run();
</script>
with
<script src="main.spec.js"></script>
You want to run mocha at the end when all your specs and setup is done.

Categories

Resources