likes
comments
collection
share

从零配置Vue开发webpack环境踩到的坑

作者站长头像
站长
· 阅读数 20

通用的基础配置略过不提,假定已经配置好了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开发webpack环境踩到的坑

[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开发webpack环境踩到的坑

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)