问题描述
我是 webpack 和类似工具的新手.我想重新组织我的项目.目前我所有的 JS 代码都在 App.js 中.因此,在将其拆分为模块并进行改进之前,我只想设置用于复制它的工作流程.这是 webpack.config.js 的内容:
I'm new to webpack and similar tools. I wanted to reorganize my project. Currently all my JS-code lives in App.js. So before splitting it into modules and improving, I wanted just to set up the workflow for copying it.This is the content of webpack.config.js:
const path = require('path');
module.exports = {
mode: 'development',
entry: {
App: "./app/assets/scripts/App.js"
},
output: {
path: path.resolve(__dirname, './app/temp/scripts'),
filename: '[name].js',
},
module: {
rules: [{
loader: 'babel-loader',
query: {
presets: ['es2015']
},
test: /\.js$/,
include: [
path.resolve(__dirname, "app")
],
exclude: [
path.resolve(__dirname, "node_modules")
],
}],
},
};
我在 这个视频课程.但之后并非所有功能都有效.例如,事件侦听器调用的函数工作:
which I learned at this video course. But afterwards not all functions work. For instance, the functions called by event listeners work:
function initOnClickForVersionBtns() {
$('#btn_soprano').click(function () {
voice = 1;
loadFile();
});
$('#btn_basset').click(function () {
voice = 2;
loadFile();
});
}
但是那些从 HTML 调用的不会:
But those called from HTML do not:
<a href="javascript:void(0);" onclick="switchToScore();">Score</a>
请注意,我仍在从 HTML 中引用其他一些 js 文件:
Note that I am still referencing few others js files from HTML:
<script src="../javascript/basic-events.js" type="text/javascript">/**/</script>
<script src="../javascript/bootstrap.min.js" type="text/javascript">/**/</script>
<script src="../javascript/jquery-3.3.1.min.js" type="text/javascript">/**/</script>
我希望稍后更改,但目前我认为这应该不是问题.也许是?
I'd like it to change later, but currently I thought it should not be a problem. Maybe it is?
推荐答案
Webpack 将所有代码包装在 IIFE 中,以实现更可预测的行为并避免全局污染等.在捆绑代码中,定义模块函数的位置不是的顶层.
Webpack wraps all code in an IIFE, for more predictable behavior and to avoid global pollution, among other things. In the bundled code, the place where your module's functions are defined is not the top level of the <script>
.
内联属性事件处理程序可能只引用全局变量.,并且几乎在所有情况下都是一个糟糕的主意.虽然您可以通过将函数显式分配给 window
来修复它,例如:
Inline attribute event handlers may only reference global variables., and are quite a bad idea in nearly all cases. While you could fix it by explicitly assigning the function to window
, eg:
window.switchToScore = function() {
// ...
代替
function switchToScore() {
// ...
最好完全删除内联属性事件处理程序,并像使用 Javascript 一样附加侦听器
It would be much better to remove the inline attribute event handlers completely, and attach listeners with Javascript, just like you're doing with
$('#btn_soprano').click(function () {
voice = 1;
loadFile();
});
这篇关于webpack 意外修改了 *.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!