[英]HTML inline javascript with webpack
我目前开始在我的网站上使用 webpack,我有一个问题。
我目前有一个 html 页面,其中包括我的 javascript 捆绑包,并且在 ZFC35FDC70D5FC69D253ECZ8 中嵌入的按钮中具有一些onclick
功能。 我想保留这些按钮和onclick
的功能,但目前我还没有找到这样做的方法。 显然,如果我尝试缩小 javascript 函数,则 function 的名称会发生变化,并且无法正常工作。
这是一个示例,其中 webpack 生成的包包含在 html 文件中:
<button onclick="foo("bar")">test</button>
并且当前foo
未定义。
我试过使用 html webpack 插件没有成功。
https://jsfiddle.net/danwillm/bkgtnm6s/
有没有办法做到这一点?
是的,您可以访问 function,但您仍然需要稍微修改代码 - 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'
})
]
}
}
最重要的部分是名称输入和输出。 您还必须导出每个 function。
JS
export function test(type) {
alert(type);
}
我们可以通过这种方式到达 function。
HTML
<a onClick="MYSCRIPT.test('bar')">click</a>
您可以在 此处找到整个设计示例。
您的脚本在 SO 片段中工作,如下所示
function foo(test){ console.log(test); }
<a onClick="foo('bar');" class="blue left desktop-only pointer">click here</a>
It did not work in jsfiddle probably because of scope issues: The script is probably executed in its own scope and a function definition there was not reachable by the onclick
in the HTML. 我修改了您的 function 定义,因此它将始终落在全局 scope
foo=function(test){console.log(test);}
现在它也可以在那里工作,请参见此处: https://jsfiddle.net/obuvjn0m/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.