vue-cli2.x升級webpack4.6.x及添加typescript支持

什麼是typescript

TypeScript 是 JavaScript的強類型版本。而後在編譯期去掉類型和特有語法,生成純粹的 JavaScript 代碼。因爲最終在瀏覽器中運行的仍然是 JavaScript,因此 TypeScript 並不依賴於瀏覽器的支持,也並不會帶來兼容性問題。javascript

TypeScript 是 JavaScript 的超集,這意味着他支持全部的 JavaScript 語法。並在此之上對 JavaScript 添加了一些擴展,如 class / interface / module 等。這樣會大大提高代碼的可閱讀性。css

與此同時,TypeScript 也是 JavaScript ES6 的超集,Google 的 Angular 2.0 也宣佈採用 TypeScript 進行開發。這更是充分說明了這是一門面向將來而且腳踏實地的語言。html

強類型語言的優點在於靜態類型檢查,具體能夠參見 www.zhihu.com/question... 的回答。歸納來講主要包括如下幾點:vue

1.靜態類型檢查
2.IDE 智能提示
3.代碼重構
4.可讀性java

一、首先vue-cli生成項目

這裏複習一下咱們的cli命令node

vue init webpack 'projectName'
複製代碼

二、安裝ts支持

安裝vue的官方插件
npm i vue-class-component vue-property-decorator --save

// ts-loader typescript 必須安裝,其餘的相信你之後也會裝上的
npm i ts-loader typescript tslint tslint-loader tslint-config-standard --save-dev
複製代碼

這些庫大致的做用,能夠按需引入:jquery

vue-class-component:強化 Vue 組件,使用 TypeScript/裝飾器 加強 Vue 組件
vue-property-decorator:在 vue-class-component 上加強更多的結合 Vue 特性的裝飾器
ts-loader:TypeScript 爲 Webpack 提供了 ts-loader,其實就是爲了讓webpack識別 .ts .tsx文件 tslint-loader跟tslint:我想你也會在.ts .tsx文件 約束代碼格式(做用等同於eslint)
tslint-config-standard:tslint 配置 standard風格的約束webpack

三、配置webpack

一、首先將main.js 修改成main.ts
二、修改webpack.base.conf.jsweb

entry: {
      app: './src/main.ts'
    }
    // TS後綴文件一如不用寫後綴
    resolve: {
        extensions: ['.js', '.vue', '.json', '.ts'],
        alias: {
          '@': resolve('src')
        }
    }
    // 若是建立項目的時候添加了eslint 還須要將 ...(config.dev.useEslint ? [createLintingRule()] : []),註釋掉並添加以下代碼
      //添加ts文件解析
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
        options: {
          appendTsSuffixTo: [/\.vue$/],
        }
      },
複製代碼

三、對vue-loader.con.js做以下修改vue-cli

//引入
    const merge = require('webpack-merge')
    並修改(添加tslint)
    module.exports = {
      loaders: merge(utils.cssLoaders({
        sourceMap: sourceMapEnabled,
        extract: isProduction
      }),{
        ts: ['ts-loader', 'tslint-loader']
      }),
      cssSourceMap: sourceMapEnabled,
      cacheBusting: config.dev.cacheBusting,
      transformToRequire: {
        video: ['src', 'poster'],
        source: 'src',
        img: 'src',
        image: 'xlink:href'
      }
    }
    
複製代碼

ts-loader 會檢索當前目錄下的 tsconfig.json 文件,根據裏面定義的規則來解析.ts文件(就跟.babelrc的做用同樣)

tslint-loader 做用等同於 eslint-loader

四、添加tsconfig.json完整配置請點擊tsconfig.json

{
      // 編譯選項
      "compilerOptions": {
        // 輸出目錄
        "outDir": "./output",
        // 是否包含能夠用於 debug 的 sourceMap
        "sourceMap": true,
        // 以嚴格模式解析
        "strict": true,
        // 採用的模塊系統
        "module": "esnext",
        // 如何處理模塊
        "moduleResolution": "node",
        // 編譯輸出目標 ES 版本
        "target": "es5",
        // 容許從沒有設置默認導出的模塊中默認導入
        "allowSyntheticDefaultImports": true,
        // 將每一個文件做爲單獨的模塊
        "isolatedModules": false,
        // 啓用裝飾器
        "experimentalDecorators": true,
        // 啓用設計類型元數據(用於反射)
        "emitDecoratorMetadata": true,
        // 在表達式和聲明上有隱含的any類型時報錯
        "noImplicitAny": false,
        // 不是函數的全部返回路徑都有返回值時報錯。
        "noImplicitReturns": true,
        // 從 tslib 導入外部幫助庫: 好比__extends,__rest等
        "importHelpers": true,
        // 編譯過程當中打印文件名
        "listFiles": true,
        // 移除註釋
        "removeComments": true,
        "suppressImplicitAnyIndexErrors": true,
        // 容許編譯javascript文件
        "allowJs": true,
        // 解析非相對模塊名的基準目錄
        "baseUrl": "./",
        // 指定特殊模塊的路徑
        "paths": {
          "jquery": [
            "node_modules/jquery/dist/jquery"
          ]
        },
        // 編譯過程當中須要引入的庫文件的列表
        "lib": [
          "dom",
          "es2015",
          "es2015.promise"
        ]
      }
}
<!--如下是個人配置------------------------------->
    {
        "include": [
          "src/**/*"
        ],
        "exclude": [
          "node_modules"
        ],
        "compilerOptions": {
          "allowSyntheticDefaultImports": true,
          "experimentalDecorators": true,
          "allowJs": true,
          "module": "esnext",
          "target": "es5",
          "moduleResolution": "node",
          "isolatedModules": true,
          "lib": [
            "dom",
            "es5",
            "es2015.promise"
          ],
          "sourceMap": true,
          "pretty": true
        }
    }
  
複製代碼

五、添加tslint.json

{
      "extends": "tslint-config-standard",
      "globals": {
        "require": true
      }
    }
複製代碼

六、讓ts識別.vue文件
因爲 TypeScript 默認並不支持 *.vue 後綴的文件,因此在 vue 項目中引入的時候須要建立一個 vue-shim.d.ts 文件,放在項目項目對應使用目錄下,例如 src/vue-shim.d.ts

//告訴ts   .vue文件交給vue處理
    declare module "*.vue" {
        import Vue from "vue";
        export default Vue;
    }
    //將html識別爲字符串
    declare module "*.html" {
        let template: string;
        export default template;
    }
複製代碼

而在代碼中導入 *.vue 文件的時候,須要寫上 .vue 後綴。緣由仍是由於 TypeScript 默認只識別 *.ts 文件,不識別 *.vue 文件:


至此vue-cli引入ts已經介紹完畢
參考 vue + typescript 新項目起手式
Vue全家桶+TypeScript使用總結

你覺得結束了?

ts須要webpack4.x的支持,咱們經過vue-cli2.x建立的項目默認使用webpack3.6.0 因此咱們還須要升級咱們項目的webpack版本
一、首先

npm i webpack-cli@2.0.15 webpack@4.6.0 css-loader@0.28.11 extract-text-webpack-plugin@4.0.0-beta.0 file-loader@1.1.11 html-webpack-plugin@3.2.0 optimize-css-assets-webpack-plugin@4.0.0 url-loader@1.0.1 vue-loader@15.0.3 vue-style-loader@4.1.0 vue-template-compiler@2.5.16 webpack-bundle-analyzer@2.11.1 webpack-dev-middleware@3.1.3 webpack-dev-server@3.1.3 webpack-hot-middleware@2.22.1 compression-webpack-plugin@1.1.11 -D
複製代碼

二、再次

npm i eslint@4.19.1 eslint-config-standard@11.0.0 eslint-friendly-formatter@4.0.1 eslint-loader@2.0.0 eslint-plugin-import@2.11.0 eslint-plugin-node@6.0.1 eslint-plugin-promise@3.7.0 eslint-plugin-standard@3.1.0 eslint-plugin-vue@4.5.0 -D
複製代碼

三、而後

// webpack.base.conf.js
const { VueLoaderPlugin } = require('vue-loader')
module.exports = {
// ...
plugins: [
new VueLoaderPlugin()
]
}
複製代碼

四、分別對開發環境和生產環境添加mode

mode: 'development'
mode: 'production'
複製代碼

五、開發環境去掉webpack4.x默認有該配置

new webpack.NamedModulesPlugin()
    new webpack.NoEmitOnErrorsPlugin()
複製代碼

六、將生產環境下面的commonschunkplugin插件配置所有去掉

new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks (module) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'app',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),
    ---------------------------------------------------------------------
    // 添加
    optimization: {
    runtimeChunk: {
      name: 'manifest'
    },
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          chunks: 'all'
        },
        'async-vendors': {
          test: /[\\/]node_modules[\\/]/,
          minChunks: 2,
          chunks: 'async',
          name: 'async-vendors'
        }
      }
    }
  }

複製代碼

七、npm run build 又會出錯 將webpack.prod.conf.js做以下修改

new ExtractTextPlugin({
  filename: utils.assetsPath('css/[name].[contenthash].css'),
  allChunks: true
}),
//改成
new ExtractTextPlugin({
  filename: utils.assetsPath('css/[name].[md5:contenthash].css'),
  allChunks: true
}),
複製代碼

webpack升級參考vue-cli#webpack3.0升級到webpack4.6

到此咱們的改造纔算大功告成

相關文章
相關標籤/搜索