Home » vue » `document` is null after webpack vue.js

`document` is null after webpack vue.js

Posted by: admin November 26, 2021 Leave a comment

Questions:

I try to build a project with vuejs and webpack.

this is my index.js

import Vue from 'vue'
import App from './app.vue'

console.log(document.body)

const root = document.createElement('div')
document.body.appendChild(root)
new Vue({
    render:(h) => h(App)
}).$mount(root)

after webpack it to bundles.js, and run it on a browser, it rises:
enter image description here

as you can see,document beacames null.

why document does not works? this bug is my problems or from vue.js?

this is my webpack.config.js:

const path = require("path")

module.exports = {
    entry:path.join(__dirname,"./src/index.js"),
    output: {
        path: path.join(__dirname,"dist"),
        filename: "bundle.js"
    },
    module:{
        rules:[
            {
                test: /\.vue$/,
                loader:"vue-loader"
            },
            {
                test:/\.css$/,
                use:[
                    'style-loader',
                    "css-loader"
                ]
            },
            {
                test:/\.(gif|jpg|jpeg|png|svg)$/,
                use:[
                    {
                        loader: "url-loader",
                        options: {
                            "limit":1024,
                            name:"[name]-aaa.[ext]"
                        }
                    }
                ]
            }
        ]
    }
}

this is package.json

{
  "description": "todolist",
  "license": "MIT",
  "scripts": {
    "build": "webpack --config webpack.config.js"
  },
  "dependencies": {
    "vue": "2.5.16"
  },
  "devDependencies": {
    "webpack-cli": "^3.0.3",
    "webpack": "^4.11.1",
    "css-loader": "^0.28.11",
    "file-loader": "^1.1.11",
    "style-loader": "^0.21.0",
    "url-loader": "^1.0.1",
    "vue-loader": "^14.2.2",/*15. 版本不行*/
    "vue-template-compiler": "^2.5.16"
  }
}
Answers:

I assume your index.js is placed in the head of your HTML and because the JavaScript resource is blocking, your body has not even been defined yet.

You need to either put the JavaScript after your elements that you are targeting, or you need to use the onload event.

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload