Function not found although it is in the bundle.js - javascript

index.html:
<script>
document.addEventListener("DOMContentLoaded", function() {
...
getXYCookieValue()
...
}
</script>
<body>
...
<script src="bundle.js" type="text/javascript"></script>
</body>
webpack-config:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
entry: __dirname + '/src/cookieHandler.js'
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
},
}
cookieHandler.js
function getXYCookieValue() {
// returns xy cookie value
}
server.js
app.use(express.static(path.join(__dirname, 'build')));
If I GET localhost:3000/bundle.js the file gets returned and i see the getXYCookieValue() function in it. However, when i try to use it in the index.html, i get the
Uncaught ReferenceError: getXYCookieValue is not defined
error.
What am i missing here?

Related

HTML error using functions from bundle.js

I've created a bundle.js file using webpack to organize all my javascript code. I was expecting to use it in my html file but having troubles using the function. An error always returns when I try to call the function index.html:9 Uncaught TypeError: App.testButton is not a function at setup.
I had the impression that if I configured the webpack with the library output specified, I would be able to access the functions via the specified library name.
What am I doing wrong?
App.js
import testButton from './testButton.js';
console.log("I'm the entry point");
testButton();
testButton.js
function testButton()
{
console.log("Test Button");
};
export default testButton;
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="dist/bundle.js"></script>
<script>
function setup()
{
console.log("Initializing a webpage");
App.testButton()
}
</script>
</head>
<body onload="setup();">
</body>
</html>
webpack.config.js
const path = require('path');
module.exports = {
entry: './app.js',
mode: 'development',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'var',
library: 'App'
},
};
I found this to work for me. I needed to modify App.js to include babel so I could use ES5 which allowed me to use require to populate module.exports.
App.js
require('babel-register')({
presets: ['env']
});
module.exports = {
testButton: require('./testButton.js'),
testButton2: require('./testButton2.js')
};
testButton.js
export function testButton()
{
console.log("Test Button");
};
testButton2.js
export function testButton()
{
console.log("Test Button 2");
};
index.html
function setup()
{
App.testButton.testButton();
App.testButton2.testButton();
}
</script>
Output in Console
Test Button
test Button 2

when I use webpack function in undefined

I use webpack in my simple project when create bundle javascript file and I am typing in console function. function undefined how prevent to undefined function
in first js file
export default function read(){
console.log("hello webpack");
}
and in main js file
import read from './def';
read();
and in console I look this error
VM51:1 Uncaught ReferenceError: read is not defined
at <anonymous>:1:1
in webpack config file
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};

webpack 4 library target umd x is not a constructor

i have this es6 class in my /src/index.js
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `(${this.x}, ${this.y})`;
}
}
export default Point;
here is the webpack.config.js file
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
library: 'point',
libraryTarget: 'umd',
umdNamedDefine: true,
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};
so when i include in my index.html file like this:
<!DOCTYPE html>
<html>
<head>
<title>Webpack</title>
</head>
<body>
<!-- Scripts -->
<script src="dist/bundle.js"></script>
<script type="text/javascript">
new point(1, 3).toString()
</script>
</body>
</html>
so i have this error in console
"Uncaught TypeError: point is not a constructor"
this is umd script type
why i'm seeing this error while compile with webpack?
same scenario working fine with rollup
is there any solution?
and one more thing i saw almost every developer use rollup for es6 package development to compile "esm", "umd" versions of the script.
but i want to use webpack instead of rollup.
any guide?
thanks
Please add libraryExport: 'default', in output section of Webpack configuration.
something like this (for your case),
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
library: 'point',
libraryTarget: 'umd',
umdNamedDefine: true,
libraryExport: 'default',
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
};

how to export function with webpack

I intend to bundle all my .js using webpack.
I tried with a very simple example as following.
Function to bundle in a test.js file :
function test() {
console.log('hello');
}
Webpack configuration :
module.exports = [{
{
output: {
filename: 'test.js',
path: __dirname + '/public/javascript/dist'
},
entry: [
'./public/javascript/test.js'
]
}
]
Code to test :
<html>
<head></head>
<body>
<script src="./javascript/dist/test.js"></script>
<script type="text/javascript">
window.onload = function()
{
test();
}
</body>
</html>
But I receive the following error : Uncaught ReferenceError: test is not defined.
Question : why?
[Edit] Reponse is : "export" is missing.
Thanks to that, I updated as following:
Code to export :
export function Test() {
this.t = 1;
Test.prototype.toto = function()
{
console.log('hello')
}
}
Webpack conf :
{
output: {
filename: 'test.js',
path: __dirname + '/public/javascript/dist',
library: 'test',
libraryTarget: 'window'
},
entry: [
'./public/javascript/poc/test.js'
]
}
To create the object, I have to do : var t = new test.Test();
It's a bit heavy... Is there a way to only have to make : var t = new Test(); ?
why?
Because you haven't exported anything from your entry point and, by default, webpack generates output in umd format without polluting global scope.
You first have to export your function:
export default function test() {
console.log('hello');
}
Then specify "library" and "libraryTarget" in your webpack config. Docs. For example:
output: {
filename: 'test.js',
path: __dirname + '/public/javascript/dist',
library: 'test',
libraryTarget: 'window',
libraryExport: 'default'
},
this will generate code that adds window.test = _entry_return_.default .
Since webpack 5 you're able to export to a variable instead of binding methods to the global window.
So when you are exporting your function like so:
export default function test() {
console.log('hello');
}
And configure the library type to var (libraryTarget in earlier versions of webpack 5):
output: {
filename: 'test.js',
path: __dirname + '/public/javascript/dist',
library: {
name: 'myLibrary',
type: 'var',
},
}
You can access your method like so:
myLibrary.test()

Javascript modules with Webpack

I'm trying to refactor client javascript in my nodejs/express application using CommonJS + Webpack modules.
With Webpack I build a 'bundle.js' made of two js files where I defined the two modules following CommongJS syntax. But on window.onload of the page I get a nice 'TypeError: moveTo.logHelloWorld is not a function" error.
Where am I wrong?
Webpack configuration:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: ['./public/js/common.js', './public/js/moveTo.js'],
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.min.js'
},
plugins: process.env.NODE_ENV === 'production' ? [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
] : []
}
moveTo.js
var moveTo = {};
console.log("moveTo.js loaded...");
moveTo.logHelloWorld = function(){
console.console.log("Hello World logHelloWorld() from moveTo client Javascript!");
};
module.exports = moveTo;
moveTo.handlebars
<div>MoveTo</div>
<script type="text/javascript">
window.onload = function(){
console.log("ON LOAD...");
moveTo.logHelloWorld();
}
</script>
and finally in the main template I included the bundle.js built with Webpack:
<script src="/bundle.min.js" type="text/javascript"></script>
And this is the error I got:
UPDATE: How to use multiple client js files
Suppose I would like to add another test.js file with its own module like so:
test.js
var test = {};
console.log("test.js loaded...");
test.logHelloWorld = function(){
console.log("Hello World logHelloWorld() from TEST client Javascript!");
};
module.exports = test;
And then in Webpack config:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: ['./public/js/common.js', './public/js/moveTo.js', './public/js/test.js'],
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.min.js',
library: ["moveTo", "test"] //This is not working.
},
plugins: process.env.NODE_ENV === 'production' ? [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
] : []
}
How may I get this to work?
UPDATE:
This is what i get using the suggested webpack configuration
#LAST UPDATE#
Apparently there is no way to have a single bundle.js and get it to work with different javascript files. This is the only thing I reached so far with the precious help of #hazardous:
webpack.config.js
var webpack = require('webpack');
var path = require('path');
// ['./public/js/common.js', './public/js/moveTo.js', './public/js/test.js'],
module.exports = {
entry: './public/js/t3toolbox.js',
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.min.js',
library: ["t3toolbox", "[name]"]
},
plugins: process.env.NODE_ENV === 'production' ? [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
] : []
}
t3toolbox.js
var t3toolbox = {}; // Global App NameSpace
var test = require('./test.js');
var moveTo = require('./moveTo.js');
t3toolbox.moveTo = moveTo;
t3toolbox.test = test;
module.exports = t3toolbox;
moveTo.js
var moveTo = {};
console.log("moveTo.js loaded...");
moveTo.logHelloWorld = function(){
console.log("Hello World logHelloWorld() from MOVETO client Javascript!");
};
module.exports = moveTo;
test.js
var test = {};
console.log("test.js loaded...");
test.logHelloWorld = function(){
console.log("Hello World logHelloWorld() from TEST client Javascript!");
};
module.exports = test;
moveTo.handlebars
moveTo
<script type="text/javascript">
window.onload = function(){
console.log("ON LOAD...");
t3toolbox.main.moveTo.logHelloWorld();
t3toolbox.main.test.logHelloWorld();
}
</script>
As you can see you still have to use the main after t3toolbox. I never accomplished the configuration where you end up with
var mylibrary = {
moveTO: {/*...*/},
test: {/*...*/}
}
It always end up with:
var mylibrary = {
main: {
moveTo: {/*...*/},
test: {/*...*/}
}
}
Try adding library to output configuration, like so -
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: ['./public/js/common.js', './public/js/moveTo.js'],
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.min.js',
library: 'moveTo'
},
plugins: process.env.NODE_ENV === 'production' ? [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
] : []
}
If your library has several exported entities, use this -
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: ['./public/js/common.js', './public/js/moveTo.js'],
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.min.js',
library: ["mylibrary", "[name]"]
},
plugins: process.env.NODE_ENV === 'production' ? [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
] : []
}
This example is based on https://github.com/webpack/webpack/blob/master/examples/multi-part-library/webpack.config.js#L10.
This example configuration will create an export of this form:
var mylibrary : {
"common": {/* exports from common */},
"moveTo": {/* exports from moveTo */}
}
So you can use them in your code using mylibrary.common, mylibrary.moveTo etc.
If you don't want to club all of your imports in "mylibrary", you can change the library to -
library:"[name]"
This will create separate var moveTo = ... and var test = ... exports.

Categories