preface

In the last article, you compiled the VUE code using WebPack. Next, upgrade JS to TS and compile TypeScript code using Webpack based on vue single-file components.

Release notes

The version of Webpack used for this article is: 4.30.0

Begin to build

The goal of this article is to complete compilation of TypeScript code in.ts files and vue single-file pages.

Install the loader

Install TypeScript on the command line and TypeScript loader:

$ cnpm install typescript ts-loader --save-dev
Copy the code

Install the official vue plug-in

$ cnpm i vue-class-component vue-property-decorator --save-dev
Copy the code

The vuE-template-compiler component needs to be installed.

$ cnpm i vue-template-compiler --save-dev
Copy the code

The package.json file is as follows:

{
  "name": "webpack_vue_ts"."version": "1.0.0"."description": ""."private": true."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."build": "webpack"
  },
  "keywords": []."author": ""."license": "ISC"."devDependencies": {
    "@babel/core": "^ 7.4.3"."@babel/preset-env": "^ 7.4.3"."babel-loader": "^ 8.0.5"."clean-webpack-plugin": "^ 2.0.1." "."css-loader": "^ 2.1.1"."file-loader": "^ 3.0.1." "."html-webpack-plugin": "^ 3.2.0"."postcss-loader": "^ 3.0.0"."precss": "^ 4.0.0"."style-loader": "^ 0.23.1"."ts-loader": "^ 5.4.3." "."typescript": "^ 3.4.5." "."vue": "^ 2.6.10"."vue-class-component": "^ 7.0.2"."vue-loader": "^ 15.7.0"."vue-property-decorator": "^ 8.1.0"."vue-template-compiler": "^ 2.6.10"."webpack": "^ 4.30.0"."webpack-cli": "^ 3.3.1"}}Copy the code

Configure ts processing rules in Webpack

Add ts file processing rules to webpack.config.js:

Module.exports = {resolve: {// add '.ts' to a resolvable extension. extensions: ['.ts'.'.js'],
    },
    module:{
        rules:[
            {
                test: /\. Ts $/, // Handles ts files, and <script lang= in vue files"ts">
                loader: 'ts-loader',
                options: { appendTsSuffixTo: [/\.vue$/] }
            },
        ]
    },
};
Copy the code

At this point, the complete webpack.config.js file looks like this:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');

module.exports = {
    entry: './src/js/index.ts'Output :{filename:'index.js? [hash]'Path :path.resolve(__dirname,'dist') // Output folder}, resolve: {// add '.ts' to a resolvable extension. extensions: ['.ts'.'.js'].alias: {
            'vue$': 'vue/dist/vue.esm.js'},}, plugins: [new CleanWebpackPlugin(), // Clean up old resources new HtmlWebpackPlugin({// generate HTML file template:'./src/index.html'}), new VueLoaderPlugin(), // Here vue needs to add an extra plug-in, to define.js,.css rules to.vue file], module:{rules:[{test: /\.js$/,
                loader: 'babel-loader'
            },
            {
                test: /\.ts$/,
                loader: 'ts-loader',
                options: { appendTsSuffixTo: [/\.vue$/] }
            },
            {
                test: /\.css$/, // Handle CSS files, and.vue files <style> use:['vue-style-loader'.'style-loader'.'css-loader'.'postcss-loader',]}, {test: / \. (PNG | SVG | JPG | GIF) $/, / / management image resource use: [{loader:'file-loader',
                        options:{
                            name:'[path][name].[ext]? [hash]'}},]}, {test: / \. (woff | woff2 | eot | the vera.ttf | otf) $/, / / management text resource use: [{loader:'file-loader',
                        options:{
                            name:'[path][name].[ext]? [hash]'// The result will keep the original file name, add hash value after the file path to avoid caching}}]}, {test: / \. (mp3 | wav | wma | ape | aac) $/ I / / management text resource use: [{loader:'file-loader',
                        options:{
                            name:'[path][name].[ext]? [hash]'// The result will keep the original file name, add hash value after the file path to avoid caching}}]}, {test:/\.vue$/, // Process.vue file loader:'vue-loader'},]}};Copy the code

Configuration TypeScript

Json file directory, you can configure ts compilation options according to the official website. The current configuration is as follows:

{
  "compilerOptions": {
    "target": "es5"."experimentalDecorators": true."strict": true."module": "es2015"."moduleResolution": "node"}}Copy the code

Add ts dependency files

Create a new project.d.ts file in the files directory and add the code to parse.vue:

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

Rewrite the entry js file to ts file

Change the entry js file./ SRC /js/index.js to ts,./ SRC /js/index.ts, and then use /// in index.ts to introduce dependent files:

///
      
Copy the code

The directory structure

My file directory structure is as follows:

webpack-vue-ts |- node_modules |- /dist |- /src |- /assets |- btn_longtap.png |- /css |- style.css |- /js |- index.ts |-  index.html |- package.json |- package-lock.json |- postcss.config.js |- project.d.ts |- tsconfig.json |- webpack.config.jsCopy the code

File directory Description:

  • ./src/js/index.tsThe file is the import file;
  • ./srcThe folder is the pre-compilation folder,./distThe folder is the compiled folder.

Add code

The complete code for the./ SRC /js/index.ts file is as follows:

///
      

import '.. /css/style.css';
import Vue from 'vue';
import App from   './App.vue';
new Vue({
    el:"#app",
    template: '<App/>',
    components:{
        App
    }
});
Copy the code

/ SRC /js/ app. vue/app. vue/SRC /js/ app. vue

<template>
    <div class="app">
        <p>{{str}}</p>
        <img src="../assets/btn_longtap.png">
    </div>
</template>

<script lang="ts">
    import { Vue, Component, Watch, Emit, Prop, } from 'vue-property-decorator';
    @Component({})// 组件在此添加
    export default class App extends Vue{
        private str:string = 'success'; // data 定义
        private mounted(){ // mounted
            console.log(this.change); // 输入 success
        }
        get change():string{ // computed
            return this.str;
        }
    }
</script>

<style scoped>
    $color_index : 1;
    .app{
        @if $color_index == 1{
            color: red;
        }@else{
            color: blue;
        }
    }
</style>
Copy the code

compiler

Run the command line

$ npm run build
Copy the code

The TypeScript code in index.ts and app. vue files is compiled successfully:

conclusion

  1. Set upwebpack,vue,TypeScriptThe combination of the three is still a bit complicated. There is no complete guide for the combination of the three, so you can only extract some configuration information from the respective documents.
  2. So far five articles have been played with WebPackes6postcssvueAs well asTypeScriptAnd other code compilation, but only as a configuration reference, as a tool for actual development, also need to optimize webPack compilation according to the Webpack document;
  3. Next, you will optimize the webPack compilation process or optimize the resource files.

Refer to the link

  • Ts-loader documentation: github.com/TypeStrong/…
  • Vue – loader documentation – use the preprocessor: vue-loader.vuejs.org/zh/guide/pr…
  • Typescrip tsconfig. Json configuration: www.tslang.cn/docs/handbo…
  • Webpack loaders document: webpack.docschina.org/loaders/
  • Webpack typescrpt guide: www.webpackjs.com/guides/type…
  • Vue-property-decorator document: github.com/kaorun343/v…
  • Vue typescript support: cn.vuejs.org/v2/guide/ty…

More articles

  • Check out other articles of netease Creative Department: github.com/f2e-netease…
  • Check out more of my articles: github.com/ningbonb/bl…