[英]Named functions in a javascript file using Webpack 4
I just started using Webpack 4 in a project and am new to Webpack. 我刚开始在一个项目中使用Webpack 4,而且是Webpack的新手。 Once Webpack 4 was implemented, I noticed that named functions kept erroring saying [functionName] is not defined.
一旦实现了Webpack 4,我注意到命名函数一直出错,说没有定义[functionName]。
I have looked quite extensively over the last few days and have tried multiple options with no success. 在过去的几天里,我已经看了很多,并尝试了多种选择但没有成功。 I am hoping for someone to help me work through this in a more direct fashion way.
我希望有人能以更直接的方式帮助我解决这个问题。
function openNav(obj) {
...do something
}
@foreach (object in list)
{
...create some HTML
}
const bundleFileName = 'bundle';
const dirName = 'wwwroot/dist';
module.exports = (env, argv) => {
return {
mode: argv.mode === "production" ? "production" : "development",
entry: [
'./src/Index.js',
'./src/css/site.css',
'./src/js/app.js'
],
output: {
filename: bundleFileName + '.js',
path: path.resolve(__dirname, dirName)
},
module: {
rules: [
{
test: /\.css$/,
use: [{ loader: 'style-loader' }, { loader: 'css-loader' }]
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: bundleFileName + '.css'
})
]
};
};
I expected the button in the razor file to send the object over to the named function so something can happen like it did previously before webpack 我期望剃刀文件中的按钮将对象发送到命名函数,这样就可以像之前在webpack之前那样发生
You've said you're trying to use openNav
from an onclick
attribute. 您已经说过要尝试使用
onclick
属性中的openNav
。 The problem there is that openNav
has to be a global to be used that way, but Webpack is a module bundler . 问题在于
openNav
必须是以这种方式使用的全局 ,但Webpack是一个模块捆绑器 。 Functions at the top level of modules aren't globals. 模块顶层的函数不是全局变量。 (Which is a good thing.)
(这是件好事。)
The solution is to not use onxyz
-attribute-style event handlers. 解决方案是不使用
onxyz
-attribute样式的事件处理程序。 Instead, use modern event handling ( addEventListener
, probably with at least some event delegation). 相反,使用现代事件处理(
addEventListener
,可能至少有一些事件委托)。
To ease your transition from the old way to the modern way, you can expose a function globally from within a module like this (on browsers): 为了简化从旧方式到现代方式的转换,您可以在这样的模块中全局公开函数(在浏览器上):
window.openNav = openNav;
I strongly recommend only doing that temporarily to make it easier to transition to modern event handling. 我强烈建议只暂时这样做,以便更容易过渡到现代事件处理。
thats because your webpack config isnt set to understand how to handle javascript files, add this to your rules key: 多数民众赞成因为您的webpack配置未设置为了解如何处理javascript文件,请将其添加到您的规则键:
{
test: /\.jsx?/,
loader: 'babel-loader'
}
you will also need to install babel loader that is in a version compatible with your babel core, for v7^ you need to install @babel/core @babel/loader etc, otherwise, babel-loader etc 你还需要安装与你的babel核心兼容的版本的babel加载器,对于v7 ^你需要安装@ babel / core @ babel / loader等,否则,babel-loader等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.