关于javascript:从零配置Vue开发webpack环境踩到的坑

3次阅读

共计 1964 个字符,预计需要花费 5 分钟才能阅读完成。

通用的根底配置略过不提,假设曾经配置好了 webpack-dev-server, 剩下的就是在配置 Vue 相干的内容时,呈现的一些报错。

1、图片不显示,门路为 [object Module] 的问题

景象

失常配置好 Vue 页面,页面也可能显示,然而图片显示不进去,查看元素,img 标签的 src 有点异样。

<img data-v-47323bf2=""src="[object Module]"alt="">

能够看到 src 字段不是一个地址,而是一个对象,所以显示不进去。

起因

查看 vue-loader 的文档,能够在解决资源门路这一章看到,vue-loader 会将所有遇到的资源 URL 转换为 webpack 模块申请。
例如,上面的模板代码片段:

<img src="../image.png">

将会被编译成为:

createElement('img', {
  attrs: {src: require('../image.png') // 当初这是一个模块的申请了
  }
})

能够看到 Vue 生成的是 CommonJS 模块语法,即 require(‘../image.png’);但 file-loader 默认采纳 ES 模块语法,即 import ‘../image.png’;二者不统一。所以在图片援用的时候就变成了 src=”[object Module]”。

解决

须要让 file-loader 或 url-loader 采纳 CommonJS 语法。刚好 file-loader 或 url-loader 有一个 esModule 选项能调整,将其设置为 false 即可:

{test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
            limit: 10000,
            name: 'static/img/[name].[hash:7].[ext]',
            esModule: false
        }
}

值得一提的是当初 webpack 中文文档里,url-loader 基本没提这个字段,仅在英文文档里有相干阐明。

2、页面空白,报 runtime-only build 相干谬误

景象

页面报如下谬误

[Vue warn]: You are using the runtime-only build of Vue where the
template compiler is not available. Either pre-compile the
templates into render functions, or use the compiler-included
build.

起因

vue 有两种模式的代码 compiler(模板)模式和 runtime 模式(运行时),vue 模块的 package.json 的 main 字段默认为 runtime 模式,指向了 ”dist/vue.runtime.common.js” 地位。
而对应的,初始化也有两种形式:

// compiler
new Vue({
  el: '#app',
  router: router,
  store: store,
  template: '<App/>',
  components: {App}
})
//runtime
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app")

我应用的就是下面的那种,于是呈现了谬误。

解决

webpack 配置文件里有个别名配置

resolve: {
    alias: {'vue$': 'vue/dist/vue.esm.js'}
}

加上这个别名,import Vue from ‘vue’ 这行代码被解析为 import Vue from ‘vue/dist/vue.esm.js’,间接指定了文件的地位,没有应用 main 字段默认的文件地位。所以在 webpack.config.js 里加上下面的配置就行了。

3、Unknown custom element: \<router-view\> 问题

景象

页面不显示,报如下谬误。

vue.esm.js:628 [Vue warn]: Unknown custom element: <router-view> -
did you register the component correctly? For recursive 
components, make sure to provide the "name" option.

起因

因为除了在文件头部间接引入 vue.js 和 vue-router.js,会在 vue-router 外部会检测 window.Vue 对象是否存在,如果存在就会主动调用 Vue.use()办法,否则须要手动调用 Vue.use(VueRouter)来确保路由插件注册到 Vue 中。

解决

在 main.js 或别的适合的中央调用 Vue.use(Router)即可。

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
正文完
 0