webpack4.29.x成神之路(二十四) 手动配置vue-cli——集成typescript

目录

上节: 手动配置vue-cli下

上节目录:

本节给之前配的vue-cli集成ts,让它支持ts + vue的开发。
首先修改build/webpack.base.js:

const HTMLPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const {resolve} = require('path');
module.exports = {
  entry: resolve(__dirname, '../src/main.ts'),
  resolve: {
    // 这里可以配置些文件后缀,用于写路径时可省略后缀(会影响打包速度,不建议配太多)
    extensions: [ '.tsx', '.ts', '.js', 'vue', 'less' ]
  },
  module: {
    rules: [{
      // 识别.vue文件
      test: /\.vue$/,
      loader: 'vue-loader'
    }, {
      // 识别.ts或.tsx文件
      test: /\.tsx?$/,
      use: 'ts-loader'
    }, {
      // 用于识别vue文件中的script块
      test: /\.js$/,
      loader: 'babel-loader',
    }, {
      test: /\.(gif|jpg|jpeg|png|svg|ttf|woff)$/,
      loader: 'url-loader'
    }]
  },
  plugins: [
    new HTMLPlugin({
      template: resolve(__dirname, '../index.html')
    }),

    // 将定义过的其它规则复制并应用到 .vue 文件里相应语言的块
    new VueLoaderPlugin()
  ]
};

在rule里加了ts规则后,通过VueLoaderPlugin也能将其用于.vue文件

然后根目录下新建tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "esNext",
    // "strict": true,
    "strictPropertyInitialization": false,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    /*"types": [
      "webpack-env"
    ],*/
    "paths": {
      "@/*": [
        "src/*"
      ],
      "*": [
        "src/*"
      ]
    },
    "lib": [
      "esNext",
      "dom",
      "dom.iterable",
      "scripthost",
      "es2015.promise"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

这是ts的配置文件,不熟的话可以复制上面的,具体选项参考官网

然后要给vue写一下类型声明,src下新建shims-vue.d.ts
src/shims-vue.d.ts:

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

如果你要写tsx语法的话再新建shims-tsx.d.ts
src/shims-tsx.d.ts:

import Vue, { VNode } from 'vue'

declare global {
  namespace JSX {
    // tslint:disable no-empty-interface
    interface Element extends VNode {}
    // tslint:disable no-empty-interface
    interface ElementClass extends Vue {}
    interface IntrinsicElements {
      [elem: string]: any
    }
  }
}

然后改一下App.vue,把ts部分改成外部引入的:
src/App.vue:



src下新建App.ts:

import { Component, Vue } from "vue-property-decorator";
  @Component({
    name: "App"
  })
  export default class App extends Vue {
    msg = 'webpack4'
  }

将src/main.js改成main.ts, 现在目录大致如下:

然后安装依赖:
npm i typescript ts-loader vue-class-component vue-property-decorator -D

然后npm run dev,打开浏览器:

试下npm run build应该也能成功打包:

下节:vue-cli与vue-loader介绍(待更新)

你可能感兴趣的:(webpack)