vue-cli3.0 特性解读

最近的开发项目中使用了vue-cli 3.0,使用体验可以说非常棒了,模板更加制定化,配置更加简洁。以下总结下应用过程中的一些经验。

新建项目

rush:js;"> # 安装 npm install -g @vue/cli # 新建项目 vue create my-project # 项目启动 npm run serve # 打包 npm run build

打包后的文件,对引用资源注入了预加载(preload/prefetch),启用 PWA 插件时注入 manifest/icon 链接,并且引入(inlines) webpack runtime / chunk manifest 清单已获得最佳性能

功能配置

功能选择

3.0 版本包括认预设配置 和 用户自定义配置,在用户自定义配置之后,会询问是否保存当前的配置功能为将来的项目配置的预设值,这样下次可直接使用不需要再次配置。

自定义功能配置包括以下功能

  1. TypeScript
  2. Progressive Web App (PWA) Support
  3. Router
  4. Vuex
  5. CSS Pre-processors
  6. Linter / Formatter
  7. Unit Testing
  8. E2E Testing

可以根据项目大小和功能体验配置不同的功能,空格键 选中/反选,按a键 全选/全不选,按i键反选已选择项, 上下键 上下移动选择。

功能细节配置

在选择功能后,会询问更细节的配置,

TypeScript:

  1. 是否使用class风格的组件语法:Use class-style component Syntax?
  2. 是否使用babel做转义:Use Babel alongside TypeScript for auto-detected polyfills?

CSS Pre-processors:

  1. 选择CSS 预处理类型:Pick a CSS pre-processor

Linter / Formatter

  1. 选择Linter / Formatter规范类型:Pick a linter / formatter config
  2. 选择lint方式,保存时检查/提交时检查:Pick additional lint features

Testing

  1. 选择Unit测试方式
  2. 选择E2E测试方式

选择 Babel,PostCSS,ESLint 等自定义配置的存放位置 Where do you prefer placing config for Babel,ESLint,etc.?

vue.config.js 自定义配置

vue.config.js完整默认配置

{},configureWebpack: () => {},// vue-loader 配置项 // https://vue-loader.vuejs.org/en/options.html vueLoader: {},// 生产环境是否生成 sourceMap 文件 productionSourceMap: true,// css相关配置 css: { // 是否使用css分离插件 ExtractTextPlugin extract: true,// 开启 CSS source maps? sourceMap: false,// css预设器配置项 loaderOptions: {},// 启用 CSS modules for all css / pre-processor files. modules: false },// use thread-loader for babel & TS in production build // enabled by default if the machine has more than 1 cores parallel: require('os').cpus().length > 1,// 是否启用dll // See https://github.com/vuejs/vue-cli/blob/dev/docs/cli-service.md#dll-mode dll: false,// PWA 插件相关配置 // see https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa pwa: {},// webpack-dev-server 相关配置 devServer: { open: process.platform === 'darwin',host: '0.0.0.0',port: 8080,https: false,hotOnly: false,proxy: null,// 设置代理 before: app => {} },// 第三方插件配置 pluginoptions: { // ... } }

设置代理

rush:js;"> # string module.exports = { devServer: { proxy: '' } }

Object

module.exports = {
devServer: {
proxy: {
'/api': {
target: '',ws: true,changeOrigin: true
},'/foo': {
target: ''
}
}
}
}

启用dll

启用dll后,我们的动态库文件每次打包生成vendor的[chunkhash]值就会一样,其值可以是 true/false,也可以制定特定的代码库。

rush:js;"> module.exports = { dll: true }

module.exports = {
dll: [
'dep-a','dep-b/some/nested/file.js'
]
}

静态资源路径

相对路径

  1. 静态资源路径以 @ 开头代表 /src
  2. 静态资源路径以 ~ 开头,可以引入node modules内的资源

public文件夹里的静态资源引用

rush:js;"> # 在 public/index.html中引用静态资源 <%= webpackConfig.output.publicPath %> nofollow" >

vue templates中,需要在data中定义baseUrl