简体   繁体   中英

Javascript - How to use a variable across two functions in webpack?

I have to migrate old, plain HTML with plain JS files to webpack but I have troubles when I have a variable declared outside functions and used between multiple functions below them.

One of the example:

// 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();
})

However, everytime recordEnd is called, JS console always throw undefined error on recorder object, as if the variable never even touched at all by the recordStart function.

Is there something that I do wrong here? I just learn webpack for a week so please bear with me if this is a rookie mistake.

PS. jQuery runs fine, if I run console.log() in them they would fire properly.

Edit: I forgot to mention this issue happens only after I run npx webpack on it with this configuration:

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>

One of the main selling points of modules is to give your code an explicit dependency chain, and to avoid global variables. For variables that you want to be able to access in other modules, you should export them, and import them where they're needed.

export let recorder;
// do stuff
// assign to recorder

and in the other module

import { recorder } from './theFirstModule';
function recordEnd() {
  recorder.stop();
}

The other (bad) option is to make recorder explicitly global, so it'll be accessible anywhere - but that defeats the purpose of using modules and makes code harder to reason about, so I wouldn't recommend it.

Instead of doing

var recorder;

, instead, wherever you assign to recorder , assign to window.recorder . (But if I were you I'd really try working within the module system first)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM