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')
}
};
Related
I have some code where I have placeholders. There are some variables that I don't know yet that I need to fill in when the code is pushed to production. Right now I have the following in a file called constants.js.
export const PublicAddress = process.env.PUBLIC_ADDRESS || console.error( "Public address is not yet set." );
This code works just fine and there will be an error logged to the console when PUBLIC_ADDRESS is empty.
However, if PUBLIC_ADDRESS was empty AND I forgot to hardcode another value, I'd like Webpack to throw an error when compiling instead. It's really important that I don't forget to put in a real value when I compile it for production.
Is that possible?
It's typically this kind of check that you can provide in your own webpack plugin. here is a basic implementation of a custom plugin that check if all string from an array refer to an env variable :
class EnvVarExistPlugin {
apply(compiler) {
const envsVarToCheck = ['TEST_VAR', 'TEST_VAR2'] // put your env var list here
envsVarToCheck.forEach(envVar => {
if (!!!process.env[envVar]) {
throw new Error(`Environment variable : ${envVar} is missing`);
}
});
}
};
module.exports = EnvVarExistPlugin
Then register your plugin in your webpack.config.js :
const { resolve } = require("path");
const EnvVarExistPlugin = require("./pathToYourPlugin");
require('dotenv').config({ path: './.env' }); // adapt path to your env file
module.exports = {
entry: resolve(__dirname, "src/index.js"),
mode: 'development',
output: {
path: resolve(__dirname, "dist"),
filename: "bundle.js"
},
plugins: [new EnvVarExistPlugin()]
};
I have experience in Javascript and jQuery, but I am new to webpack.
I have a file called test1.js:
exports.func1 = function() {
window.alert('hello from func 1');
};
I then have index.js, which contains the following:
import test1 from "./test1"
My webpack.config.js contains:
const path = require('path');
module.exports = {
entry: './index.js',
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist'), //folder to put the output file
},
};
I have included app.js into my webpage and that is fine, no errors in console about file cannot be found. I want to call func1() from a button click, for example, <button onclick="func1()">Test</button>.
When I do this I get "func1 is not defined" in console output. Webpack doesn't show any errors when I run it, so it must be the way I am calling the function somehow.
I must be doing something, or not doing something, really stupid. Can someone help as I seem to be going round in circles? Thanks.
It's because test1 is the exported object. func1 is a property of test1.
test1.func1() will invoke the function
You could also import it by destructuring. Try the following:
import { func1 } from './test1'
Change test1.js to:
export default () => {
window.alert('hello from func 1');
};
Then in your index.js:
export { default as test1 } from "./test1"
If you want to consume in HTML you should build a library and update your webpack like below:
const path = require('path');
module.exports = {
entry: './index.js',
output: {
filename: 'app.js',
path: path.resolve(__dirname, 'dist'), //folder to put the output file
library: 'myApp',
libraryTarget: 'umd',
},
};
Now your function is exported and should be available for usage.
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
I thought by exporting specific functions and use it will only include this function in a compiled file but it doesn't seem so ex:
file1:
export function redu1(state = null, action) {
return state;
}
export function redu2(state = null, action) {
return state;
}
file2:
import {redu1} from './file1';
What did i see in the compiled file that all the functions are included?
According to Webpack Tree Shaking, you should set property mode to production in your webpack.config.js file to remove dead code from bundle.
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'production'
};
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?