小程序开发攻略:官方小程序技术能力规划、自定义组件

2018-09-0713:21:50APP与小程序开发Comments2,994 views字数 24266阅读模式

自定义组件2.0

小程序的几个页面间,存在一些相同或是类似的区域,这时候可以把这些区域逻辑封装成一个自定义组件,代码就可以重用,或者对于比较独立逻辑,也可以把它封装成一个自定义组件,也就是微信去年发布的自定义组件,它让代码得到复用、减少代码量,更方便模块化,优化代码架构组织,也使得模块清晰,后期更好地维护,从而保证更好的性能。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

但微信打算在原来的基础上推出的自定义组件 2.0,它将拥有更高级的性能:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • usingComponents 计划支持全局定义和通配符定义:这意味着不用在每个页面反复定义,可以批量导入目录下的所有自定义组件
  • 计划支持类似 Computed 和 watch 的功能,它能使代码逻辑更清晰
  • 计划支持 Component 构造器插件,在实例化一个自定义组件的时候,允许你在构造器的这个阶段,加入一些逻辑,方便进行一些扩展,甚至是可以扩展成 Vue 的语法

npm支持

目前小程序开发的痛点是:开源组件要手动复制到项目,后续更新组件也需要手动操作。不久的将来,小程序将支持npm包管理,有了这个之后,想要引入一些开源的项目就变得很简单了,只要在项目里面声明,然后用简单的命令安装,就可以使用了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

官方自定义组件

微信小程序团队表示,他们在考虑推出一些官方自定义组件,为什么不内置到基础库里呢?因为内置组件要提供给开发者,这个组件一定是开发者很难实现或者是无法实现的一个能力。所以他们更倾向于封装成自定义组件,想基于这些内置组件里,封装一些比较常见的、交互逻辑比较复杂的组件给大家使用,让大家更容易开发。类似弹幕组件,开发者就不用关注弹幕怎么飘,可以节省开发者的开发成本。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

同时,他们也想给开发者提供一些规范和一些模板,让开发者设计出好用的自定义组件,更好地被大家去使用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

添加体验评分

当小程序加载太慢时,可能会导致用户的流失,而小程序的开发者可能会面临着不知道如何定位问题或不知如何解决问题的困境。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

为此,小程序即将推出一个体验评分的功能,这是为了帮助开发者可以检查出小程序有一些什么体验不好的地方,也会同时给出一份优化的指引建议。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

原生组件同层渲染

小程序在最初的技术选型时,引入了原生组件的概念,因为原生组件可以使小程序的能力更加丰富,比如地图、音视频的能力,但是原生组件是由客户端原生渲染的,导致了原生组件的层级是最高的,开发者很容易遇到打开调试的问题,发现视频组件挡在了 vConsole 上。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

为了解决这个问题,当时微信做了一个过渡的方案:cover-view。cover-view可以覆盖在原生组件之上,这一套方案解决了大部分的需求场景。比如说视频组件上很多的按钮、标题甚至还有动画的弹幕,这些都是用 cover-view 去实现的,但它还是没有完全解决原生组件的开发体验问题,因为 cover-view 有一些限制:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • 无法与其他组件混在一起渲染
  • 没有完整的触摸事件
  • cover-view 对样式的表现有差异
  • cover-view 对样式的支持度不够高

因此微信决定将用同层渲染取代 cover-view,它能像普通组件一样使用,原生组件的层级不再是最高,而是和其他的非原生组件在同一层级渲染,可完全由 z-index 控制,可完全支持触摸事件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

微信表示,同层渲染在 iOS 平台小程序上已经开始内测,会很快开放给开发者,Android 平台已经取得突破性进展,目前正在做一轮封装的工作,开放指日可待。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

wepy vs mpvue

数据流管理

相比传统的小程序框架,这个一直是我们作为资深开发者比较期望去解决的,在 Web 开发中,随着 Flux、Redux、Vuex 等多个数据流工具出现,我们也期望在业务复杂的小程序中使用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • WePY 默认支持 Redux,在脚手架生成项目的时候可以内置
  • Mpvue 作为 Vue 的移植版本,当然支持 Vuex,同样在脚手架生成项目的时候可以内置

组件化

如果你和我们一样,经历了从无到有的小程序业务开发,建议阅读【小程序的组件化开发】章节,进行官方语法的组件库开发(从基础库 1.6.3 开始,官方提供了组件化解决方案)。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • WePY 类似 Vue 实现了单文件组件,最大的差别是文件后缀 .wpy,只是写法上会有差异,具体可以查看【主流框架使用案例 1:WePY】章节,学习起来有一定成本,不过也会很快适应:
export default class Index extends wepy.page {}
复制代码
  • Mpvue 作为 Vue 的移植版本,支持单文件组件,template、script 和 style 都在一个 .vue 文件中,和 vue 的写法类似,所以对 Vue 开发熟悉的同学会比较适应。

工程化

所有的小程序开发依赖官方提供的开发者工具。开发者工具简单直观,对调试小程序很有帮助,现在也支持腾讯云(目前我们还没有使用,但是对新的一些开发者还是有帮助的),可以申请测试报告查看小程序在真实的移动设备上运行性能和运行效果,但是它本身没有类似前端工程化中的概念和工具。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • wepy 内置了构建,通过 wepy init 命令初始化项目,大致流程如下:
  • wepy-cli 会判断模版是在远程仓库还是在本地,如果在本地则会立即跳到第 3 步,反之继续进行。
  • 会从远程仓库下载模版,并保存到本地。
  • 询问开发者 Project name 等问题,依据开发者的回答,创建项目。
  • mpvue 沿用了 vue 中推崇的 webpack 作为构建工具,但同时提供了一些自己的插件以及配置文件的一些修改,比如:
  • 不再需要 html-webpack-plugin
  • 基于 webpack-dev-middleware 修改成 webpack-dev-middleware-hard-disk
  • 最大的变化是基于 webpack-loader 修改成 mpvue-loader
  • 但是配置方式还是类似,分环境配置文件,最终都会编译成小程序支持的目录结构和文件后缀。

综合比较

对比\框架微信小程序mpvuewepy
语法规范小程序开发规范vue.js类vue.js
标签集合小程序htm l + 小程序小程序
样式规范wxsssass,less,postcsssass,less,styus
组件化无组件化机制vue规范自定义组件规范
多段复用不可复用支持h5支持h5
自动构建无自动构建webpack框架内置
上手成本全新学习vue 学习vue 和 wepy
数据管理不支持vuexredux

选型的个人看法

先说结论:选择 mpvue。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

wepy vs mpvue。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

理由:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

工程化 原生开发因为不带工程化,诸如NPM包(未来会引入)、ES7、图片压缩、PostCss、pug、ESLint等等不能用。如果自己要搭工程化,不如直接使用wepy或mpvue。mpvue和wepy都可以和小程序原生开发混写。参考mpvue-echart参考wepy。 而问题在于wepy没有引入webpack(wepy@2.0.x依然没有引入),以上说的这些东西都要造轮子(作者造或自己造)。没有引入 Webpack 是一个重大的硬伤。社区维护的成熟 Webpack 显然更稳定,轮子更多。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

维护 wepy 也是社区维护的,是官方的?其实 wepy 的主要开发者只有作者一人,附上一个contrubutors链接。另外被官方招安了也是后来的事,再说腾讯要有精力帮着一起维护好 wepy,为什么不花精力在小程序原生开发上呢?再来看看 mpvue,是美团一个前端小组维护的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

学习成本 Vue 的学习曲线比较平缓。mpvue 是 Vue的子集。所以 mpvue 的学习成本会低于 wepy。尤其是之前技术栈有学过用过 Vue 的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

未来规划 mpvue 已经支持 web 和小程序。因为 mpvue 基于AST,所以未来可以支持支付宝小程序和快应用。他们也是有这样的规划。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

请在需求池下面自己找文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

小程序开发攻略:官方小程序技术能力规划、自定义组件

两者都有各自的坑。但是我觉得有一些wepy的坑是没法容忍的。比如repeat组建里面用computed得到的列表全是同一套数据而且1.x是没法解决的。 wepy和mpvue我都开发过完整小程序的体验下,我觉得wepy的坑更多,而且wepy有些坑碍于架构设计没办法解决。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

mpvue

Vue.js 小程序版, fork 自 vuejs/vue@2.4.1,保留了 vue runtime 能力,添加了小程序平台的支持。 mpvue 是一个使用 Vue.js 开发小程序的前端框架。框架基于 Vue.js 核心,mpvue 修改了 Vue.js 的 runtime 和 compiler 实现,使其可以运行在小程序环境中,从而为小程序开发引入了整套 Vue.js 开发体验。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

框架原理

两个大方向文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • 通过mpvue提供 mp 的 runtime 适配小程序
  • 通过mpvue-loader产出微信小程序所需要的文件结构和模块内容。

七个具体问题文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

要了解 mpvue 原理必然要了解 Vue 原理,这是大前提。但是要讲清楚 Vue 原理需要花费大量的篇幅,不如参考learnVue文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

现在假设您对 Vue 原理有个大概的了解。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

由于 Vue 使用了 Virtual DOM,所以 Virtual DOM 可以在任何支持 JavaScript 语言的平台上操作,譬如说目前 Vue 支持浏览器平台或 weex,也可以是 mp(小程序)。那么最后 Virtual DOM 如何映射到真实的 DOM 节点上呢?vue为平台做了一层适配层,浏览器平台见 runtime/node-ops.js、weex平台见runtime/node-ops.js,小程序见runtime/node-ops.js。不同平台之间通过适配层对外提供相同的接口,Virtual DOM进行操作Real DOM节点的时候,只需要调用这些适配层的接口即可,而内部实现则不需要关心,它会根据平台的改变而改变。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

所以思路肯定是往增加一个 mp 平台的 runtime 方向走。但问题是小程序不能操作 DOM,所以 mp 下的node-ops.js 里面的实现都是直接 return obj文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

新 Virtual DOM 和旧 Virtual DOM 之间需要做一个 patch,找出 diff。patch完了之后的 diff 怎么更新视图,也就是如何给这些 DOM 加入 attr、class、style 等 DOM 属性呢? Vue 中有 nextTick 的概念用以更新视图,mpvue这块对于小程序的 setData 应该怎么处理呢?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

另外个问题在于小程序的 Virtual DOM 怎么生成?也就是怎么将 template 编译成render function。这当中还涉及到运行时-编译器-vs-只包含运行时,显然如果要提高性能、减少包大小、输出 wxml、mpvue 也要提供预编译的能力。因为要预输出 wxml 且没法动态改变 DOM,所以动态组件,自定义 render,和<script type="text/x-template"> 字符串模版等都不支持(参考)。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

另外还有一些其他问题,最后总结一下文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • 1.如何预编译生成render function
  • 2.如何预编译生成 wxml,wxss,wxs
  • 3.如何 patch 出 diff
  • 4.如何更新视图
  • 5.如何建立小程序事件代理机制,在事件代理函数中触发与之对应的vue组件事件响应
  • 6.如何建立vue实例与小程序 Page 实例关联
  • 7.如何建立小程序和vue生命周期映射关系,能在小程序生命周期中触发vue生命周期

platform/mp的目录结构文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

.
├── compiler //解决问题1,mpvue-template-compiler源码部分
├── runtime //解决问题3 4 5 6 7
├── util //工具方法
├── entry-compiler.js //mpvue-template-compiler的入口。package.json相关命令会自动生成mpvue-template-compiler这个package。
├── entry-runtime.js //对外提供Vue对象,当然是mpvue
└── join-code-in-build.js //编译出SDK时的修复
复制代码

后面的内容逐步解答这几个问题,也就弄明白了原理文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

mpvue-loader

mpvue-loadervue-loader 的一个扩展延伸版,类似于超集的关系,除了vue-loader 本身所具备的能力之外,它还会利用mpvue-template-compiler生成render function文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • entry

它会从 webpack 的配置中的 entry 开始,分析依赖模块,并分别打包。在entry 中 app 属性及其内容会被打包为微信小程序所需要的 app.js/app.json/app.wxss,其余的会生成对应的页面page.js/page.json/page.wxml/page.wxss,如示例的 entry 将会生成如下这些文件,文件内容下文慢慢讲来:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

// webpack.config.js
{
    // ...
    entry: {
        app: resolve('./src/main.js'),               // app 字段被识别为 app 类型
        index: resolve('./src/pages/index/main.js'),   // 其余字段被识别为 page 类型
        'news/home': resolve('./src/pages/news/home/index.js')
    }
}

// 产出文件的结构
.
├── app.js
├── app.json
├──· app.wxss
├── components
│   ├── card$74bfae61.wxml
│   ├── index$023eef02.wxml
│   └── news$0699930b.wxml
├── news
│   ├── home.js
│   ├── home.wxml
│   └── home.wxss
├── pages
│   └── index
│       ├── index.js
│       ├── index.wxml
│       └── index.wxss
└── static
    ├── css
    │   ├── app.wxss
    │   ├── index.wxss
    │   └── news
    │       └── home.wxss
    └── js
        ├── app.js
        ├── index.js
        ├── manifest.js
        ├── news
        │   └── home.js
        └── vendor.js
复制代码
  • wxml 每一个 .vue 的组件都会被生成为一个 wxml 规范的 template,然后通过 wxml 规范的 import 语法来达到一个复用,同时组件如果涉及到 props 的 data 数据,我们也会做相应的处理,举个实际的例子:
<template>
    <div class="my-component" @click="test">
        <h1>{{msg}}</h1>
        <other-component :msg="msg"></other-component>
    </div>
</template>
<script>
import otherComponent from './otherComponent.vue'

export default {
  components: { otherComponent },
  data () {
    return { msg: 'Hello Vue.js!' }
  },
  methods: {
    test() {}
  }
}
</script>
复制代码

这样一个 Vue 的组件的模版部分会生成相应的 wxml文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

<import src="components/other-component$hash.wxml" />
<template name="component$hash">
    <view class="my-component" bindtap="handleProxy">
        <view class="_h1">{{msg}}</view>
        <template is="other-component$hash" wx:if="{{ $c[0] }}" data="{{ ...$c[0] }}"></template>
    </view>
</template>
复制代码

可能已经注意到了 other-component(:msg="msg") 被转化成了 。mpvue 在运行时会从根组件开始把所有的组件实例数据合并成一个树形的数据,然后通过 setData 到 appData,$c是 $children 的缩写。至于那个 0 则是我们的 compiler 处理过后的一个标记,会为每一个子组件打一个特定的不重复的标记。 树形数据结构如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

// 这儿数据结构是一个数组,index 是动态的
{
  $child: {
    '0'{
      // ... root data
      $child: {
        '0': {
          // ... data
          msg: 'Hello Vue.js!',
          $child: {
            // ...data
          }
        }
      }
    }
  }
}
复制代码
  • wxss

这个部分的处理同 web 的处理差异不大,唯一不同在于通过配置生成 .css 为 .wxss ,其中的对于 css 的若干处理,在 postcss-mpvue-wxss 和 px2rpx-loader 这两部分的文档中又详细的介绍。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

app.json/page.json 1.1.1 以上文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

推荐和小程序一样,将 app.json/page.json 放到页面入口处,使用 copy-webpack-plugin copy 到对应的生成位置。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

1.1.1 以下文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

这部分内容来源于 app 和 page 的 entry 文件,通常习惯是 main.js,你需要在你的入口文件中 export default { config: {} },这才能被我们的 loader 识别为这是一个配置,需要写成 json 文件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

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

const vueApp = new Vue(App);
vueApp.$mount();

// 这个是我们约定的额外的配置
export default {
    // 这个字段下的数据会被填充到 app.json / page.json
    config: {
        pages: ['static/calendar/calendar', '^pages/list/list'], // Will be filled in webpack
        window: {
            backgroundTextStyle: 'light',
            navigationBarBackgroundColor: '#455A73',
            navigationBarTitleText: '美团汽车票',
            navigationBarTextStyle: '#fff'
        }
    }
};
复制代码

同时,这个时候,我们会根据 entry 的页面数据,自动填充到 app.json 中的 pages 字段。 pages 字段也是可以自定义的,约定带有 ^ 符号开头的页面,会放到数组的最前面。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

style scoped 在 vue-loader 中对 style scoped 的处理方式是给每个样式加一个 attr 来标记 module-id,然后在 css 中也给每条 rule 后添加 [module-id],最终可以形成一个 css 的“作用域空间”。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

在微信小程序中目前是不支持 attr 选择器的,所以我们做了一点改动,把 attr 上的 [module-id] 直接写到了 class 里,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

<!-- .vue -->
<template>
    <div class="container">
        // ...
    </div>
</template>
<style scoped>
    .container {
        color: red;
    }
</style>

<!-- vue-loader -->
<template>
    <div class="container" data-v-23e58823>
        // ...
    </div>
</template>
<style scoped>
    .container[data-v-23e58823] {
        color: red;
    }
</style>

<!-- mpvue-loader -->
<template>
    <div class="container data-v-23e58823">
        // ...
    </div>
</template>
<style scoped>
    .container.data-v-23e58823 {
        color: red;
    }
</style>
复制代码
  • compiler

生产出的内容是:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

(function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// mpvue-template-compiler会利用AST预编译生成一个render function用以生成Virtual DOM。
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
  // _c创建虚拟节点,参考https://github.com/Meituan-Dianping/mpvue/blob/master/packages/mpvue/index.js#L3606
  // 以及https://github.com/Meituan-Dianping/mpvue/blob/master/packages/mpvue/index.js#L3680
  return _c('div', {
    staticClass: "my-component"
  }, [_c('h1', [_vm._v(_vm._s(_vm.msg))]), _vm._v(" "), _c('other-component', {
    attrs: {
      "msg": _vm.msg,
      "mpcomid": '0'
    }
  })], 1)
}

// staticRenderFns的作用是静态渲染,在更新时不会进行patch,优化性能。而staticRenderFns是个空数组。
var staticRenderFns = []
render._withStripped = true
var esExports = { render: render, staticRenderFns: staticRenderFns }
/* harmony default export */ __webpack_exports__["a"] = (esExports);
if (false) {
  module.hot.accept()
  if (module.hot.data) {
     require("vue-hot-reload-api").rerender("data-v-54ad9125", esExports)
  }
}

/***/ })
复制代码

compiler

compiler相关,也就是template预编译这块,可以参考《聊聊Vue的template编译》来搞明白。原理是一样的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

mpvue自己实现了export { compile, compileToFunctions, compileToWxml }(链接)其中compileToWxml是用来生成wxml,具体代码在这文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

另外mpvue是不需要提供运行时-编译器的,虽然理论上是能够做到的。因为小程序不能操作DOM,即便提供了运行时-编译器也产生不了界面。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

详细讲解compile过程:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

1.将vue文件解析成模板对象文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

// mpvue-loader/lib/loader.js
var parts = parse(content, fileName, this.sourceMap)
复制代码

假如vue文件源码如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

<template>
  <view class="container-bg">
    <view class="home-container">
      <home-quotation-view v-for="(item, index) in lists" :key="index" :reason="item.reason" :stockList="item.list" @itemViewClicked="itemViewClicked" />
    </view>
  </view>
</template>

<script lang="js">
import homeQuotationView from '@/components/homeQuotationView'
import topListApi from '@/api/topListApi'

export default {
  data () {
    return {
      lists: []
    }
  },
  components: {
    homeQuotationView
  },
  methods: {
    async loadRankList () {
      let {data} = await topListApi.rankList()
      if (data) {
        this.dateTime = data.dt
        this.lists = data.rankList.filter((item) => {
          return !!item
        })
      }
    },
    itemViewClicked (quotationItem) {
      wx.navigateTo({
        url: `/pages/topListDetail/main?item=${JSON.stringify(quotationItem)}`
      })
    }
  },
  onShow () {
    this.loadRankList()
  }
}
</script>

<style lang="stylus" scoped>
  .container-bg
    width 100%
    height 100%
    background-color #F2F4FA

  .home-container
    width 100%
    height 100%
    overflow-x hidden

</style>
复制代码

调用parse(content, fileName, this.sourceMap) 函数得到的结果大致如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

{
  template: {
    type: 'template',
    content: '\n<view class="container-bg">\n  <view class="home-container">\n    <home-quotation-view v-for="(item, index) in lists" :key="index" :reason="item.reason" :stockList="item.list" @itemViewClicked="itemViewClicked" />\n  </view>\n</view>\n',
    start: 10,
    attrs: {},
    end: 251
  },
  script: {
    type: 'script',
    content: '\n\n\n\n\n\n\n\n\nimport homeQuotationView from \'@/components/homeQuotationView\'\nimport topListApi from \'@/api/topListApi\'\n\nexport default {\n  data () {\n    return {\n      lists: []\n    }\n  },\n  components: {\n    homeQuotationView\n  },\n  methods: {\n    async loadRankList () {\n      let {data} = await topListApi.rankList()\n      if (data) {\n        this.dateTime = data.dt\n        this.lists = data.rankList.filter((item) => {\n          return !!item\n        })\n      }\n    },\n    itemViewClicked (quotationItem) {\n      wx.navigateTo({\n        url: `/pages/topListDetail/main?item=${JSON.stringify(quotationItem)}`\n      })\n    }\n  },\n  onShow () {\n    this.loadRankList()\n  }\n}\n',
    start: 282,
    attrs: {
      lang: 'js'
    },
    lang: 'js',
    end: 946,
    ...
  },
  styles: [{
    type: 'style',
    content: '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n.container-bg\n  width 100%\n  height 100%\n  background-color #F2F4FA\n\n.home-container\n  width 100%\n  height 100%\n  overflow-x hidden\n\n',
    start: 985,
    attrs: [Object],
    lang: 'stylus',
    scoped: true,
    end: 1135,
    ...
  }],
  customBlocks: []
}
复制代码

2.调用mpvue-loader/lib/template-compiler/index.js导出的接口并传入上面得到的html模板:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

var templateCompilerPath = normalize.lib('template-compiler/index')
...
var defaultLoaders = {
  html: templateCompilerPath + templateCompilerOptions,
  css: options.extractCSS
    ? getCSSExtractLoader()
    : styleLoaderPath + '!' + 'css-loader' + cssLoaderOptions,
  js: hasBuble ? ('buble-loader' + bubleOptions) : hasBabel ? babelLoaderOptions : ''
}

// check if there are custom loaders specified via
// webpack config, otherwise use defaults
var loaders = Object.assign({}, defaultLoaders, options.loaders)
复制代码
  1. 调用mpvue/packages/mpvue-template-compiler/build.js的compile接口:
// mpvue-loader/lib/template-compiler/index.js
var compiled = compile(html, compilerOptions)
复制代码

compile方法生产下面的ast(Abstract Syntax Tree)模板,render函数和staticRenderFns文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

{
  ast: {
    type: 1,
    tag: 'view',
    attrsList: [],
    attrsMap: {
      class: 'container-bg'
    },
    parent: undefined,
    children: [{
      type: 1,
      tag: 'view',
      attrsList: [],
      attrsMap: {
        class: 'home-container'
      },
      parent: {
        type: 1,
        tag: 'view',
        attrsList: [],
        attrsMap: {
          class: 'container-bg'
        },
        parent: undefined,
        children: [
          [Circular]
        ],
        plain: false,
        staticClass: '"container-bg"',
        static: false,
        staticRoot: false
      },
      children: [{
        type: 1,
        tag: 'home-quotation-view',
        attrsList: [{
          name: ':reason',
          value: 'item.reason'
        }, {
          name: ':stockList',
          value: 'item.list'
        }, {
          name: '@itemViewClicked',
          value: 'itemViewClicked'
        }],
        attrsMap: {
          'v-for': '(item, index) in lists',
          ':key': 'index',
          ':reason': 'item.reason',
          ':stockList': 'item.list',
          '@itemViewClicked': 'itemViewClicked',
          'data-eventid': '{{\'0-\'+index}}',
          'data-comkey': '{{$k}}'
        },
        parent: [Circular],
        children: [],
        for: 'lists',
        alias: 'item',
        iterator1: 'index',
        key: 'index',
        plain: false,
        hasBindings: true,
        attrs: [{
          name: 'reason',
          value: 'item.reason'
        }, {
          name: 'stockList',
          value: 'item.list'
        }, {
          name: 'eventid',
          value: '\'0-\'+index'
        }, {
          name: 'mpcomid',
          value: '\'0-\'+index'
        }],
        events: {
          itemViewClicked: {
            value: 'itemViewClicked',
            modifiers: undefined
          }
        },
        eventid: '\'0-\'+index',
        mpcomid: '\'0-\'+index',
        static: false,
        staticRoot: false,
        forProcessed: true
      }],
      plain: false,
      staticClass: '"home-container"',
      static: false,
      staticRoot: false
    }],
    plain: false,
    staticClass: '"container-bg"',
    static: false,
    staticRoot: false
  },
  render: 'with(this){return _c(\'view\',{staticClass:"container-bg"},[_c(\'view\',{staticClass:"home-container"},_l((lists),function(item,index){return _c(\'home-quotation-view\',{key:index,attrs:{"reason":item.reason,"stockList":item.list,"eventid":\'0-\'+index,"mpcomid":\'0-\'+index},on:{"itemViewClicked":itemViewClicked}})}))])}',
  staticRenderFns: [],
  errors: [],
  tips: []
}
复制代码

其中的render函数运行的结果是返回VNode对象,其实render函数应该长下面这样:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

(function() {
  with(this){
    return _c('div',{   //创建一个 div 元素
      attrs:{"id":"app"}  //div 添加属性 id
      },[
        _m(0),  //静态节点 header,此处对应 staticRenderFns 数组索引为 0 的 render 函数
        _v(" "), //空的文本节点
        (message) //三元表达式,判断 message 是否存在
         //如果存在,创建 p 元素,元素里面有文本,值为 toString(message)
        ?_c('p',[_v("\n    "+_s(message)+"\n  ")])
        //如果不存在,创建 p 元素,元素里面有文本,值为 No message. 
        :_c('p',[_v("\n    No message.\n  ")])
      ]
    )
  }
})
复制代码

其中的_c就是vue对象的createElement方法 (创建元素),_mrenderStatic(渲染静态节点),_vcreateTextVNode(创建文本dom),_stoString (转换为字符串)文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

// src/core/instance/render.js
export function initRender (vm: Component) {
  ...
  // bind the createElement fn to this instance
  // so that we get proper render context inside it.
  // args order: tag, data, children, normalizationType, alwaysNormalize
  // internal version is used by render functions compiled from templates
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  // normalization is always applied for the public version, used in
  // user-written render functions.
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
  ...
}

...
Vue.prototype._s = toString
...
Vue.prototype._m = renderStatic
...
Vue.prototype._v = createTextVNode
...
复制代码
  1. 调用compileWxml方法生产wxml模板,这个方法最终会调用 mpvue/packages/mpvue-template-compiler/build.js的compileToWxml方法将第一步compile出来的模板转成小程序的wxml模板
// mpvue-loader/lib/template-compiler/index.js
compileToWxml.call(this, compiled, html)
复制代码

以上解答了问题1、2文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

runtime

目录结构文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

.
├── events.js //解答问题5
├── index.js //入口提供Vue对象,以及$mount,和各种初始化
├── liefcycle //解答问题6、7
├── node-ops.js //操作真实DOM的相关实现,因为小程序不能操作DOM,所以这里都是直接返回
├── patch.js //解答问题3
└── render.js //解答问题4
复制代码

patch.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

和vue使用的createPatchFunction保持一致,任然是旧树和新树进行patch产出diff,但是多了一行this.$updateDataToMP()用以更新。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

render.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

两个核心的方法initDataToMPupdateDataToMP文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

initDataToMP收集vm上的data,然后调用小程序Page示例的setData渲染。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

updateDataToMP在每次patch,也就是依赖收集发现数据改变时更新(参考patch.js代码),这部分一样会使用nextTick和队列。最终使用了节流阀throttleSetData。50毫秒用来控制频率以解决频繁修改Data,会造成大量传输Data数据而导致的性能问题。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

其中collectVmData最终也是用到了formatVmData。尤其要注意的是一句注释:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

getVmData 这儿获取当前组件内的所有数据,包含 props、computed 的数据文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

我们又知道,service到view是两个线程间通信,如果Data含有大量数据,增加了传输数据量,加大了传输成本,将会造成性能下降。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

events.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

正如官网所说的,这里使用eventTypeMap做了各事件的隐射文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

import { getComKey, eventTypeMap } from '../util/index'
复制代码
// 用于小程序的 event type 到 web 的 event
export const eventTypeMap = {
  tap: ['tap', 'click'],
  touchstart: ['touchstart'],
  touchmove: ['touchmove'],
  touchcancel: ['touchcancel'],
  touchend: ['touchend'],
  longtap: ['longtap'],
  input: ['input'],
  blur: ['change', 'blur'],
  submit: ['submit'],
  focus: ['focus'],
  scrolltoupper: ['scrolltoupper'],
  scrolltolower: ['scrolltolower'],
  scroll: ['scroll']
}
复制代码

使用了handleProxyWithVue方法来代理小程序事件到vue事件。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

另外看下作者自己对这部分的思路文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

事件代理机制:用户交互触发的数据更新通过事件代理机制完成。在 Vue.js 代码中,事件响应函数对应到组件的 method, Vue.js 自动维护了上下文环境。然而在小程序中并没有类似的机制,又因为 Vue.js 执行环境中维护着一份实时的虚拟 DOM,这与小程序的视图层完全对应,我们思考,在小程序组件节点上触发事件后,只要找到虚拟 DOM 上对应的节点,触发对应的事件不就完成了么;另一方面,Vue.js 事件响应如果触发了数据更新,其生命周期函数更新将自动触发,在此函数上同步更新小程序数据,数据同步也就实现了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

getHandle这个方法应该就是作者思路当中所说的:找到对应节点,然后找到handle。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

lifecycle.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

initMP方法中,自己创建小程序的App、Page。实现生命周期相关方法,使用callHook代理兼容小程序App、Page的生命周期。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

官方文档生命周期中说到了:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

同 vue,不同的是我们会在小程序 onReady 后,再去触发 vue mounted 生命周期文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

这部分查看,onReady之后才会执行next,这个next回调最终是vue的mountComponent。可以在index.js中看到。这部分代码也就是解决了"小程序生命周期中触发vue生命周期"。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

export function initMP (mpType, next) {
  // ...
    global.Page({
      // 生命周期函数--监听页面初次渲染完成
      onReady () {
        mp.status = 'ready'

        callHook(rootVueVM, 'onReady')
        next()
      },
    })
  // ...
}
复制代码

在小程序onShow时,使用$nextTick去第一次渲染数据,参考上面提到的render.js。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

export function initMP (mpType, next) {
  // ...
  global.Page({
    // 生命周期函数--监听页面显示
    onShow () {
      mp.page = this
      mp.status = 'show'
      callHook(rootVueVM, 'onShow')

      // 只有页面需要 setData
      rootVueVM.$nextTick(() => {
        rootVueVM._initDataToMP()
      })
    },
  })
  // ...
}
复制代码

在mpvue-loader生成template时,比如点击事件@click会变成bindtap="handleProxy",事件绑定全都会使用handleProxy这个方法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

可以查看上面mpvue-loader回顾一下。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

最终handleProxy调用的是event.js中的handleProxyWithVue文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

export function initMP (mpType, next) {
  // ...
    global.Page({
      handleProxy (e) {
        return rootVueVM.$handleProxyWithVue(e)
      },
    })
  // ...
}
复制代码

index.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

最后index.js就负责各种初始化和mount。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

Class和Style为什么暂不支持组件

原因:目前的组件是使用小程序的 template 标签实现的,给组件指定的class和style是挂载在template标签上,而template 标签不支持 class 及 style 属性。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

解决方案: 在自定义组件上绑定class或style到一个props属性上。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

 // 组件ComponentA.vue
 <template>
  <div class="container" :class="pClass">
    ...
  </div>
</template>
复制代码
<script>
    export default {
    props: {
      pClass: {
        type: String,
        default: ''
      }
    }
  }
</script>
复制代码
<!--PageB.vue-->
<template>
    <component-a :pClass="cusComponentAClass"  />
</template>
复制代码
<script>
data () {
    return {
      cusComponentAClass: 'a-class b-class'
    }
  }
</script>
复制代码
<style lang="stylus" scoped>
  .a-class
    border red solid 2rpx
  .b-class
    margin-right 20rpx
</style>
复制代码

但是这样会有问题就是style加上scoped之后,编译模板生成的代码是下面这样的:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

 .a-class.data-v-8f1d914e {
   border: #f00 solid 2rpx;
 }
 .b-class.data-v-8f1d914e {
   margin-right 20rpx
 }
复制代码

所以想要这些组件的class生效就不能使用scoped的style,改成下面这样,最好自己给a-class和b-class加前缀以防其他的文件引用这些样式:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

 <style lang="stylus">
  .a-class
    border red solid 2rpx
  .b-class
    margin-right 20rpx
</style>

<style lang="stylus" scoped>
  .other-class
    border red solid 2rpx
    
   ...
</style>
复制代码
  • 在定义组件上绑定style属性到一个props属性上:
 <!--P组件ComponentA.vue-->
 <template>
  <div class="container" :style="pStyle">
    ...
  </div>
</template>
复制代码
<script>
  export default {
    props: {
      pStyle: {
        type: String,
        default: ''
      }
    }
  }
</script>
复制代码
<!--PageB.vue-->
<template>
    <component-a :pStyle="cusComponentAStyle"  />
</template>
复制代码
<script>
const cusComponentAStyle = 'border:red solid 2rpx; margin-right:20rpx;'
data () {
    return {
      cusComponentAStyle
    }
  }
</script>
复制代码
<style lang="stylus" scoped>
  ...
</style>
复制代码

也可以通过定义styleObject,然后通过工具函数转化为styleString,如下所示:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

const bstyle = {
  border: 'red solid 2rpx',
  'margin-right': '20rpx'
}
let arr = []
for (let [key, value] of Object.entries(bstyle)) {
  arr.push(`${key}: ${value}`)
}

const cusComponentAStyle = arr.join('; ')
复制代码
  • 当然自定义组件确定只会改变某个css样式,通过pros传入单个样式的值,然后通过:style绑定肯定没问题:
<!--组件ComponentA.vue-->
 <template>
  <div class="container" :style="{'background-color': backgroundColor}">
    ...
  </div>
</template>
复制代码
<script>
    export default {
    props: {
      backgroundColor: {
        type: String,
        default: 'yellow'
      }
    }
  }
</script>
复制代码
<!-- PageB.vue -->
<template>
    <component-a backgroundColor="red"  />
</template>
复制代码

分包加载

package.json修改文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • 升级: "mpvue-loader": "^1.1.2-rc.4" "webpack-mpvue-asset-plugin": "^0.1.1"
  • 新增: "relative": "^3.0.2"

注意事项文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • 1.1.2-rc.5 修复 slot 文件路径生成错误的问题
  • 1.1.x 版本还不是很稳定,对稳定性要求较高的项目建议暂时使用 1.0.x 版本

移动src/main.js中config相关内容到同级目录下main.json(新建)中文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

export default {
  // config: {...} 需要移动
}

复制代码

to文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

{
 "pages": [
   "pages/index/main",
   "pages/logs/main"
  ],
  "subPackages": [
    {
      "root": "pages/packageA",
     "pages": [
       "counter/main"
     ]
   }
 ],
 "window": {...}
}
复制代码

webpack 配置配合升级指南文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

  • 本次升级意在调整生成文件目录结构,对依赖的文件由原来的写死绝对路径该改为相对路径
  • mpvue-loader@1.1.2-rc.4 依赖 webpack-mpvue-asset-plugin@0.1.0 做依赖资源引用
  • 之前写在 main.js 中的 config 信息,需要在 main.js 同级目录下新建 main.json 文件,使用 webapck-copy-plugin copy 到 build 目录下
  • app.json 中引用的图片不会自动 copy 到 dist 目录下 json 配置文件是由 webapck-copy-plugin copy 过去的,不会处理依赖,可以将图片放到根目录下 static 目录下,使用 webapck-copy-plugin copy 过去

build/webpack.base.conf.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

+var CopyWebpackPlugin = require('copy-webpack-plugin')
+var relative = require('relative')

 function resolve (dir) {
   return path.join(__dirname, '..', dir)
 }

-function getEntry (rootSrc, pattern) {
-  var files = glob.sync(path.resolve(rootSrc, pattern))
-  return files.reduce((res, file) => {
-    var info = path.parse(file)
-    var key = info.dir.slice(rootSrc.length + 1) + '/' + info.name
-    res[key] = path.resolve(file)
-    return res
-  }, {})
+function getEntry (rootSrc) {
+  var map = {};
+  glob.sync(rootSrc + '/pages/**/main.js')
+  .forEach(file => {
+    var key = relative(rootSrc, file).replace('.js', '');
+    map[key] = file;
+  })
+   return map;
 }

   plugins: [
-    new MpvuePlugin()
+    new MpvuePlugin(),
+    new CopyWebpackPlugin([{
+      from: '**/*.json',
+      to: 'app.json'
+    }], {
+      context: 'src/'
+    }),
+    new CopyWebpackPlugin([ // 处理 main.json 里面引用的图片,不要放代码中引用的图片
+      {
+        from: path.resolve(__dirname, '../static'),
+        to: path.resolve(__dirname, '../dist/static'),
+        ignore: ['.*']
+      }
+    ])
   ]
 }
复制代码

build/webpack.dev.conf.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

module.exports = merge(baseWebpackConfig, {
   devtool: '#source-map',
   output: {
     path: config.build.assetsRoot,
-    filename: utils.assetsPath('js/[name].js'),
-    chunkFilename: utils.assetsPath('js/[id].js')
+    filename: utils.assetsPath('[name].js'),
+    chunkFilename: utils.assetsPath('[id].js')
   },
   plugins: [
     new webpack.DefinePlugin({
    module.exports = merge(baseWebpackConfig, {
     // copy from ./webpack.prod.conf.js
     // extract css into its own file
     new ExtractTextPlugin({
-      filename: utils.assetsPath('css/[name].wxss')
+      filename: utils.assetsPath('[name].wxss')
     }),
    module.exports = merge(baseWebpackConfig, {
       }
     }),
     new webpack.optimize.CommonsChunkPlugin({
-      name: 'vendor',
+      name: 'common/vendor',
       minChunks: function (module, count) {
         // any required modules inside node_modules are extracted to vendor
         return (
        module.exports = merge(baseWebpackConfig, {
       }
     }),
     new webpack.optimize.CommonsChunkPlugin({
-      name: 'manifest',
-      chunks: ['vendor']
+      name: 'common/manifest',
+      chunks: ['common/vendor']
     }),
-    // copy custom static assets
-    new CopyWebpackPlugin([
-      {
-        from: path.resolve(__dirname, '../static'),
-        to: config.build.assetsSubDirectory,
-        ignore: ['.*']
-      }
-    ]),

复制代码

build/webpack.prod.conf.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html


    var webpackConfig = merge(baseWebpackConfig, {
   devtool: config.build.productionSourceMap ? '#source-map' : false,
   output: {
     path: config.build.assetsRoot,
-    filename: utils.assetsPath('js/[name].js'),
-    chunkFilename: utils.assetsPath('js/[id].js')
+    filename: utils.assetsPath('[name].js'),
+    chunkFilename: utils.assetsPath('[id].js')
   },
   plugins: [
    var webpackConfig = merge(baseWebpackConfig, {
     }),
     // extract css into its own file
     new ExtractTextPlugin({
-      // filename: utils.assetsPath('css/[name].[contenthash].css')
-      filename: utils.assetsPath('css/[name].wxss')
+      // filename: utils.assetsPath('[name].[contenthash].css')
+      filename: utils.assetsPath('[name].wxss')
     }),
     // Compress extracted CSS. We are using this plugin so that possible
     // duplicated CSS from different components can be deduped.
    var webpackConfig = merge(baseWebpackConfig, {
     new webpack.HashedModuleIdsPlugin(),
     // split vendor js into its own file
     new webpack.optimize.CommonsChunkPlugin({
-      name: 'vendor',
+      name: 'common/vendor',
       minChunks: function (module, count) {
         // any required modules inside node_modules are extracted to vendor
         return (
     var webpackConfig = merge(baseWebpackConfig, {
     // extract webpack runtime and module manifest to its own file in order to
     // prevent vendor hash from being updated whenever app bundle is updated
     new webpack.optimize.CommonsChunkPlugin({
-      name: 'manifest',
-      chunks: ['vendor']
-    }),
+      name: 'common/manifest',
+      chunks: ['common/vendor']
+    })
-    // copy custom static assets
-    new CopyWebpackPlugin([
-      {
-        from: path.resolve(__dirname, '../static'),
-        to: config.build.assetsSubDirectory,
-        ignore: ['.*']
-      }
-    ])
   ]
 })
复制代码

config/index.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html


module.exports = {
     env: require('./prod.env'),
     index: path.resolve(__dirname, '../dist/index.html'),
     assetsRoot: path.resolve(__dirname, '../dist'),
-    assetsSubDirectory: 'static', // 不将资源聚合放在 static 目录下
+    assetsSubDirectory: '',
     assetsPublicPath: '/',
     productionSourceMap: false,
     // Gzip off by default as many popular static hosts such as
@@ -26,7 +26,7 @@ module.exports = {
     port: 8080,
     // 在小程序开发者工具中不需要自动打开浏览器
     autoOpenBrowser: false,
-    assetsSubDirectory: 'static', // 不将资源聚合放在 static 目录下
+    assetsSubDirectory: '',
     assetsPublicPath: '/',
     proxyTable: {},
     // CSS Sourcemaps off by default because relative paths are "buggy"

作者:夕阳
链接:https://juejin.im/post/5b8fd1416fb9a05cf3710690
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/xcx/4462.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/xcx/4462.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定