Calling webpacked code from outside (HTML script tag)
It seems that you want to expose the webpack bundle as a library. You can configure webpack to expose your library in the global context within a variable of your own, like EntryPoint
.
I don't know TypeScript so the example uses plain JavaScript instead. But the important piece here is the webpack configuration file, and specifically the output
section:
webpack.config.js
module.exports = {
entry: './index.js',
output: {
path: './lib',
filename: 'yourlib.js',
libraryTarget: 'var',
library: 'EntryPoint'
}
};
index.js
module.exports = {
run: function () {
console.log('run from library');
}
};
Then you will be able to access your library methods like you expect:
<script src="lib/yourlib.js"></script>
<script>
window.onload = function () {
EntryPoint.run();
};
</script>
Check the gist with the actual code.
Accessing function in bundled javascript (using webpack) from HTML file
Generally using text-based event handlers isn't a good idea. That said, you have a few options, with increasing amounts of changes.
For texual
onchange
handlers to work,sendMessage
would have to be a global. So the quickest fix would be to change your code to do that. If for instance you havefunction sendMessage(arg){}
in your code, you'd add an additional
window.sendMessage = sendMessage;
after it to expose it as a global variable.
A more modern approach would be to remove the
onchange
from the button and have the button labeled with an ID in the HTML, e.g.id="some-button-id"
.Then in your JS code, you could do
var button = document.querySelector("#some-button-id");
button.addEventListener("change", function(){
sendMessage(document.getElementById('claim').value);
});to add the
change
handler function using JS code, instead of with HTML attributes.
server render script tag outside of webpack build
It's so simple but a little complicated, first I explain all approach, then show in code.
You should consider a folder for all of JavaScript
files that they are out of webpack
build. Then put them into this folder and then import it as externals
into webpack
configuration. then set it as a separate vendor file, and absolutely output file name should make dynamically, so the webpack
build its bundle and then copy your JavaScript
file into dist folder. follow below:
// webpack.config.js
...
module.exports = {
...
externals: {
separateFile: `${srcRoot}/outFiles/yourJavaScriptFile.js`,
},
...
};
By using the above code you consider a folder for your JavaScirpt
file and import it into webpack
configuration as a externals
config.
Now you should import it as a separate file alongside your application files. see below:
// webpack.config.js
...
module.exports = {
...
entry: {
myFile: 'separateFile', // <== its your external imported file
app: `${srcRoot}/app/index.js`, // <== its your app file
},
output: {
path: '/dist',
filename: '[name].js' // <== dynamically make your JavaScript files,
// so, in dist folder you can see app.js and
// myFile.js file
}
...
};
Definitely, you should import these files to your template function, hence:
...
res.status(200).send(`
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
${styles}
${title}
</head>
<body>
<div id="root">${appString}</div>
<script src="app.js" defer></script>
<script src="myFile.js" defer></script>
</body>
</html>
`);
...
HTML inline javascript with webpack
Yes you can get to the function but you will still have to modify the code slightly - onClick.
webpack
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
module.exports = (env, argv) => {
return {
devtool: argv.mode === 'production' ? 'none' : 'source-map',
mode: argv.mode === 'production' ? 'production' : 'development',
entry: {
MYSCRIPT: './sources/script.js'
},
output: {
path: path.resolve(__dirname, './dist'),
filename: './[name].js',
library: '[name]',
libraryTarget: 'var',
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}, ]
},
plugins: [
new CleanWebpackPlugin({
verbose: true
}),
new HtmlWebPackPlugin({
filename: 'index.html',
template: './sources/index.html'
})
]
}
}
The most important part is the name entry and outputs.
You must also export each function.
JS
export function test(type) {
alert(type);
}
And we can get to the function this way.
HTML
<a onClick="MYSCRIPT.test('bar')">click</a>
You can find the whole devising example here.
Related Topics
Onclick to Get the Id of the Clicked Button
Load and Execution Sequence of a Web Page
Using an HTML Button to Call a JavaScript Function
Why Js Function Name Conflicts With Element Id
Full-Screen Iframe With a Height of 100%
Determine If an HTML Element'S Content Overflows
Converting HTML String into Dom Elements
What Is the Htmlspecialchars Equivalent in JavaScript
Maximum Size of a ≪Canvas≫ Element
Make Header and Footer Files to Be Included in Multiple HTML Pages
JavaScript - Append HTML to Container Element Without Innerhtml
Animate Element to Auto Height With Jquery
How to Make HTML Element Resizable Using Pure JavaScript
How to Escape a Single Quote ( ' ) in JavaScript
Using Queryselector With Ids That Are Numbers