Evanss
Evanss

Reputation: 23593

Browser console not seeing JavaScript variables using Webpack's dev server

Im using Webpack's dev server. It loads up a working page fine however I don't have access to JavaScript variables in my browser console. EG if I have the following in a JavaScript file:

const body = document.querySelector('body');

Then entering body in my browser console says its not defined.

Im using Webpack 3.5.5 (latest). Im running the build script from my package.json:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "watch": "webpack --watch",
    "start": "webpack-dev-server --open"
  },

In my webpack.config.js I was specifying the devServer but removing it seems to make no difference.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
  entry: './src/script.js',
  /*
  devServer: {
    contentBase: './dist'
  },
  */

Is this a configuration issue or is there another way that your supposed to access JavaScript variables?

Upvotes: 1

Views: 1570

Answers (1)

Peter
Peter

Reputation: 12711

I think this is the expected behavior. Webpack wraps the content of your script.js file into a module. Any variables you declare in there will be private. If you need to access a variable in the browser console, you can attach it to the window object.

const body = document.querySelector('body');
window.body = body;

Upvotes: 2

Related Questions