美文网首页
You are using the runtime-only b

You are using the runtime-only b

作者: Mr老朝 | 来源:发表于2020-05-26 18:38 被阅读0次

原因分析

在项目配置的时候,默认 npm 包导出的是运行时构建,即 runtime 版本,不支持编译 template 模板。

vue 在初始化项目配置的时候,有两个运行环境配置的版本:Compiler 版本、Runtime 版本。

其主要区别在于:

  • Compiler 版本:
    可以对 template 模板内容进行编译(包括字符串模板和可以绑定的 html 对象作为模板),例如:
new Vue({
  el: "#box",
  template: "<div>{{msg}}</div>",
  data: {
    msg: "hello"
  }

  • Runtime 版本:
    使用 vue-loader 加载.vue 文件(组件文件)时,webpack 在打包过程中对模板进行了渲染。

解决方法

一、 vue cli 2.x

找到 webpack.base.conf.js 文件,修改以下配置:

在 webpack.base.conf.js 配置文件中多加了一段代码,将 vue/dist/ package.json 配置文件的"main": "dist/vue.runtime.common.js",改为引用代码中的引用 vue/dist.vue.esm.js 文件,意思就是说 webpack.base.conf.js 这个文件已经将 vue/dist.package.json 的错误引用纠正成 vue/dist.vue.esm.js

// ...
const config = {
  // ...
  resolve: {
    extensions: [".js", ".vue", ".json"],
    alias: {
      vue$: "vue/dist/vue.esm.js",
      "@": resolve("src")
    }
  }

二、 vue cli 3.x

修改项目根目录中的配置文件:vue.config.js,具体代码如下:

修改 vue_cli3.0 的配置文件,添加 配置文件:vue.config.js 在项目的根目录下,目的是修改在引入 vue 时,不要采用 runtime 形式的文件,而采用 dist/vue.esm.js 形式文件

// ...
 
module.exports = {
  // ...
 
  configureWebpack: config => {
    config.resolve = {
      extensions: [".js", ".vue", ".json", ".css"],
      alias: {
        vue$: "vue/dist/vue.esm.js",
        "@": resolve("src")
      }
    };
  }
 
  // ...

三、runtimeCompiler配置

发现了一个新的方法,只需要添加一行代码的配置,即可实现支持template编译:

// vue.config.js
 
module.exports = {
  runtimeCompiler: true,

四、render替换template

// compiler
new Vue({
  el: '#app',
  router: router,
  store: store,
  template: '<App/>',
  components: { App }
})
// compiler
new Vue({
  template: '{{ hi }}'
})

替换为

//runtime
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app")
//runtime
new Vue({
  render (h) {
    return h('div', this.hi)
  }
})

相关文章

网友评论

      本文标题:You are using the runtime-only b

      本文链接:https://www.haomeiwen.com/subject/sngbohtx.html