Vue.js+TypeScript

初始化工程

vue init webpack simple

工程结构如下:

  • simple/
    • build/
      • webpack.base.conf.js
    • src/
      • components/
        • Hello.vue
        • Count.vue
      • App.vue
      • main.js

TypeScript 安装与配置

npm i -g typescript

在工程根目录simple/下,执行tsc --init生成tsconfig.json,更改配置如下:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "ESNext",                     /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": [
      "dom",
      "es5",
      "es2015.promise",
      "es2017",
      "esnext"
      ],                              /* Specify library files to be included in the compilation:  */
    "allowJs": true,                       /* Allow javascript files to be compiled. */

    /* Strict Type-Checking Options */
    "strict": true,                            /* Enable all strict type-checking options. */

    /* Module Resolution Options */
    "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */

    /* Experimental Options */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true         /* Enables experimental support for emitting type metadata for decorators. */
  }
}

Webpack 配置调整

npm i --save-dev typescript ts-loader

打开simple/build/webpack.base.conf.js,修改配置如下:

module.exports = {
  entry: {
    app: './src/main.ts'  // 将 main.js 重名为 main.ts 后,这里也要改
  },
...
  resolve: {
    extensions: ['.js', '.vue', '.json', '.ts'],  // 添加 .ts
    ...
  },
  module: {
    rules: [
      // 添加 ts-loader
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
        options: {
          appendTsSuffixTo: [/\.vue$/],
        }
      },
      ...
    ]
  }
}

babel 配置

npm i --save-dev babel-plugin-transform-decorators-legacy babel-plugin-transform-class-properties

打开simple/.babelrc,添加配置:

"plugins": [
    "transform-decorators-legacy",
    "transform-class-properties",
    ...
  ]

单文件组件(Single File Components)

声明.vue文件为单文件组件,从中提取代码。
创建simple/src/sfc.d.ts,并写入如下内容:

declare module "*.vue" {
    import Vue from 'vue'
    export default Vue
}

组件配置

npm i --save-dev vue-class-component
npm i --save-dev vue-property-decorator
  • vue-property-decorator 完全依赖于 vue-class-component,可以只使用任意一种。

main.js

  • 重命名 main.jsmain.ts

App.vue


Hello.vue




Count.vue






参考

Microsoft TypeScript Vue Starter
Vue.js TypeScript 支持
Writing Class-Based Components with Vue.js and TypeScript
vue-class-component
vue-property-decorator


你可能感兴趣的:(Vue.js+TypeScript)