我必須將帶有純 JS 檔案的舊純 HTML 遷移到,webpack但是當我在函式外部宣告一個變數并在它們下面的多個函式之間使用時,我遇到了麻煩。
示例之一:
// import stuff
var recorder;
var blobs = [];
function recordStart() {
recorder = new MediaRecorder(...);
blobs = []
recorder.ondataavailable = (event) => {
console.log("recording");
if (event.data) blobs.push(event.data);
};
recorder.onstop = function(){...};
recorder.start();
}
function recordEnd() {
recorder.stop();
}
$('#capture_button').on('touchstart mousedown', function() {
recordStart();
})
$('#capture_button').on('touchend mouseup', function() {
recordEnd();
})
但是,每次recordEnd呼叫時,JS 控制臺總是undefined在recorder物件上拋出錯誤,就好像該recordStart函式根本沒有觸及該變數一樣。
我在這里做錯了什么嗎?我剛學webpack了一個星期,所以如果這是一個菜鳥的錯誤,請多多包涵。
PS。jQuery 運行良好,如果我console.log()在其中運行,它們會正常觸發。
編輯:我忘了提到這個問題只有在我npx webpack使用這個配置運行它之后才會發生:
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
optimization: {
minimize: false,
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif|glb|gltf|usdz)$/i,
type: 'asset/resource',
}
]
},
plugins: [
new CopyPlugin({
patterns: [
{from: "src/images", to: "images"},
{from: "src/maps", to: "maps"},
{from: "src/models", to: "models"}
]
})
]
};
It runs well before I migrate to webpack, but after I bundled with it and include the dist/bundle.js in the HTML in dist/index.html the undefined error happens.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Webpack Title</title>
<script src="./bundle.js"></script>
</head>
<body>
...
</body>
</html>
uj5u.com熱心網友回復:
模塊的主要賣點之一是為您的代碼提供明確的依賴鏈,并避免使用全域變數。對于您希望能夠在其他模塊中訪問的變數,您應該使用export它們,并import在需要它們的地方使用它們。
export let recorder;
// do stuff
// assign to recorder
在另一個模塊中
import { recorder } from './theFirstModule';
function recordEnd() {
recorder.stop();
}
另一個(不好的)選項是recorder明確地全域化,所以它可以在任何地方訪問——但這違背了使用模塊的目的,并且使代碼更難推理,所以我不推薦它。
而不是做
var recorder;
,相反,無論您分配給recorder,分配給window.recorder。(但如果我是你,我真的會先嘗試在模塊系統中作業)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/406588.html
標籤:
上一篇:給出一個改變字串變數的字串
