[英]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.