gpt4 book ai didi

javascript - webpack 为浏览器编译 javascript

转载 作者:行者123 更新时间:2023-11-29 20:50:53 24 4
gpt4 key购买 nike

感谢您的关注!我已经使用 webpack 从我的源代码构建了一个 javascript 文件,我打算在浏览器中使用它,但它似乎不适合我,所以我发布这个寻求帮助这是我的项目树

project
├── dist
│   └── my-dist.js
├── index.js
├── lib
│   └── my-source.js
└── webpack.config.js

这是我的 source.js

'use strict'

const somepackage = require("somepackage")

module.exports = MyPkg

function MyPkg(param) {
this.myprop = param
}

MyPkg.prototype.Afunc = function () {
consolg.log("hello from A ", this.myprop)
}

MyPkg.prototype.Bfunc = function (param) {
// B do some thing
}

这是我的 index.js

exports = module.exports = require('./lib/MyPkg');

这是我的 webpack.config.js

const path = require('path')
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-dist.js'
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
}]
}
}

然后我运行“webpack”来构建文件,看起来没问题,并且创建了“my-dist.js”文件,所以我尝试像这样使用它:

<html>
<head>
</head>
<body>
<div>
<button onclick="func()">click here</button>
</div>
</body>
<script src="dist/my-dist.js"></script>
<script>
var pkg = new MyPkg('haha')
function func() {
pkg.Afunc()
}
</script>
</html>

但它抛出类似“Uncaught ReferenceError: MyPkg is not defined”的错误,我真的不知道如何解决它,请帮帮我,谢谢你们~

最佳答案

编辑 x2:这是一个带有进一步解释的 GitHub Repo: https://github.com/superjose/webpack-simple-example


如果我没记错的话,我以前遇到过这个问题。 Webpack 入口文件中的 JavaScript,这样其他文件或代码就无法直接访问它。

因此,在您的 index.html 中,这将不起作用

<script>
var pkg = new MyPkg('haha')
function func() {
pkg.Afunc()
}
</script>

您需要做的是使用 EventListeners,这样您就可以定位元素。

所以你有这个按钮:(添加类或 id 以更好地识别它)

 <button onclick="func()" id="js-pkg">click here</button>

然后,内部 index.js:

document.addEventListener('DOMContentLoaded', () => {
document.getElementById('js-pkg').addEventListener(MyPkg);
// This also works:
// document.querySelector('#js-pkg').addEventListener(MyPkg);
});

注意:我们添加了“DOMContentLoaded”事件,以便在进行任何操作之前等待加载 DOM。不这样做,可能会导致按钮未定义,因为它可能不会被浏览器的引擎解析或呈现

编辑:下面更详细的方法

假设您有以下结构:

----index.html
----index.js
----Email/
---------email.js
----Validator/
---------validator.js

而 index.js 是您的主要入口文件(Webpack 加载 JavaScript 的地方)。

Email.js 内容:

// Ficticious/non-existent npm package
import email from 'send-email'
// Custom and ficticious email class that will send emails
export class Email {
sendEmail(subject, message) {
// You would send the email somehow.
email.send('contact@support.com' this.subject, message);
}
}

Validator.js 内容:

// Checks if the value is undefined or null
module.exports = function (value) {
return !!value
}

在你的 index.html 中:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="name" id="js-name" placeholder="message" />
<textarea id="js-msg" placeholder="Write us a message"></textarea>
<button id="js-send">Send us a message!!</button>
<!-- Awful Real-life example -->
<button id="js-validate">Validate Text!</button>
<script src="index.js"></script>
</body>
</html>

在 index.js(Webpack 的主文件)中:

// We import the email class that we want to use
import { Email } from './Email/email.js'
// We also add validator
import validator from './Validator/validator.js'

/**
* Now the actual magic. Webpack scopes the variable and function names, changing
* the normal values, in order (I could be wrong with this) to avoid collisions with other functions, and variables.
*
* Nonetheless, JavaScript allow us to programatically attach those functions to the element via event listeners.
* https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
* This means that <input type="button" onclick="func()" /> the onclick() event is the same
* as element.addEventListener('click', func); Where element is the <input type="button" found via a document.getElementById/querySelector/querySelectorAll/getElementsByTagName/etc

* Therefore, even if Webpack scopes the variable and function names, we would be able to attach it since it resides inside Webpack's code.

* The first thing we do is to add a "DOMContentLoaded" event. This is similar to jQuery's $(document).ready(function() { }); We need for the HTML to be loaded in order for us to add the event listener. You didn't have that problem in the past because you would add it directly to the HTML.
**/

document.addEventListener('DOMContentLoaded', () => {
let sendEmail = document.getElementById('js-send');
let name = document.getElementById('js-name');
let email = new Email();
let validateBtn = document.getElementById('js-validate');
// We pass the functions without parenthesis.
// Note that validator is a function, while Email is a class.
// Email needs to be instantiated first, and then we assign
// the method that it calls.
validateBtn.addEventListener('click', validator);
sendEmail.addEventListener('click', email.sendEmail);

});

关于javascript - webpack 为浏览器编译 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51933068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com