Reputation: 13
I started recently using Webpack and came across this issue. I have a 'copyright.js' file where I export a function as a module. In the 'index.js' file I require the 'copyright.js'.In my 'webpack.config.js' I output an 'app.bundle.js' file where I can see the 'getCopyright()' function after the build.
How can I call the function in the html script tag so that I can return the value? So far I get 'Can't find variable getCopyright' or when I call 'copyright.getCopyright();' I get 'Can't find variable copyright'.
Thank you.
copyright.js
module.exports.getCopyright = function(){
var val = document.write(new Date().getFullYear());
return val;
}
webpackconfig.js
module.exports = {
entry: {
app: './src/index.js',
filename1: './src/filename1.js',
filename2: './src/filename2.css'
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].bundle.js'
},
index.js
var copyright = require('./copyright');
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="app.bundle.js"></script>
</head>
<body>
<div class="foot">
<script>getCopyright();</script>
</div>
</body>
</html>
Upvotes: 1
Views: 2230
Reputation: 10167
Everything in webpack is a module. Even your non-modular code gets packed into a module. var copyright
(index.js) is not in the global scope, so when you run your script tag copyright is not accessible.
You can of course do:
window.copyright = require('./copyright');
But then we are straight back to using global objects. (Of course, if you are writing some web-library that should be included by others, then you have to expose something to the browser sooner or later.)
With webpack there are ways to inline scripts in the html if you absolutely want to , but the good solution is to run your stuff from a module and not from a script-tag (which is using the global environment).
So run your code from your index.js (it is the reason you have declared it to be an entry-point after all):
let copyright = require('./copyright');
copyright.getCopyright();
(And yeah, that does make document.write() just a little bit counter-productive.)
Upvotes: 1