0

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"
  }
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Shuai Li
  • 2,426
  • 4
  • 24
  • 43
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Emile Bergeron Jun 07 '18 at 20:02

1 Answers1

2

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

Stephan-v
  • 19,255
  • 31
  • 115
  • 201