javascript - webpack 为浏览器编译 javascript

标签 javascript node.js webpack

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

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

这里是 my-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


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

因此,在您的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('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9995948e9b998eba898f8a8a95888ed4999597" rel="noreferrer noopener nofollow">[email protected]</a>' 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/

相关文章:

javascript - 是否可以使用 WebRTC getusermedia 和 HTML5 访问整个屏幕?

node.js - 如何使用 NGINX 访问写入 docker 容器卷上的文件并将 URL 共享到客户端

javascript - 为什么在带有 Bootstrap 的 Rails 6 中使用 webpacker 时我的 js.erb View 不起作用?

reactjs - 如何在 HTML &lt;script src =""中引用 process.env 变量? react

javascript - 从分割字符串中解构混合的 let/const 数组

javascript window.open 没有为不同的网址打开不同的窗口?

javascript - 如何向express.js 页面添加 Angular ?

javascript - 如何在 sequelize 中使用事务?

reactjs - 使用 React-Bootstrap 的 Webpack,大量 'Module Not Found' 错误

javascript - 优化 javascript/coffeescript 中的视差滚动