webpack+Vue+ts+仿写element-ui源码3(持续更新)

468 阅读1分钟

大家好,我是robert,今天是用webpack从0开发一个ts版的element源码系列教程3(js文件变更为ts)


作者:robert
仓库地址:gitee.com/dawwdadfrf/…

最近在学习element的源码,想着学习element的时候来顺便把webpack,css,ts方面的知识也学一学,因为是第一次分享,过程中可能存在着很多的不足之处。请大家多多指教。本项目适用于小伙伴入门,文章将持续更新
仓库地址:gitee.com/dawwdadfrf/…


一. 引入ts文件

1.安装ts相关的依赖保

  npm install --save-dev typescript       
  npm install --save-dev ts-loader    

2.在根目录增加tsconfig.json

{
    "include": [
      "src/**/*",
      "packages/**/*",
      "examples/**/*",
      "examples/**/*.vue",
      ".vue"
    ],
    "exclude": [
      "node_modules"
    ],
    "typeAcquisition": {
      "enable": true
    },
    "files": [
      "./vue-shim.d.ts"
    ],
    "compilerOptions": {
      "allowSyntheticDefaultImports": true,
      "experimentalDecorators": true,
      "allowJs": true,
      "module": "esnext",
      "target": "es5",
      "moduleResolution": "node",
      "baseUrl": ".", // 工作根目录
      "isolatedModules": true,
      "lib": [
        "dom",
        "es5",
        "es6",
        "es7",
        "es2015.promise"
      ],
      "jsxFactory": "h",
      "sourceMap": true,
      "pretty": true,
      "paths": { // 指定模块的路径,和baseUrl有关联,和webpack中resolve.alias配置一样
        "main": [ //指定后可以在文件之直接 import * from 'src';
          "./src"
        ],
      },
    }
  }

3.将examples下面的main.js文件更改为main.ts文件

4.查看此时examples下面的main.ts的内容,找不到模块app

5.在跟目录创建vue-shim.d.ts 用于声明vue文件

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

6.修改webpack.config.js文件,增加以下内容

rules: [
{
  test: /\.tsx?$/,
  exclude: /node_modules/
}]

7.此时为webpack.config.js最后的文件内容为

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
  module.exports = {
    entry: './examples/main.ts',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, '../dist')
    },
    devServer: {
      host: '127.0.0.1',
      port: 8085,
      publicPath: '/',
      hot: true
    },
    plugins: [
      new HtmlWebpackPlugin({           //打包生成新的html文件
        template: './examples/index.tpl',
      }),
      new VueLoaderPlugin(),
    
    ],
    module: {
      rules: [
        {
          test: /\.vue$/,
          loader: 'vue-loader'
        },
        {
          test: /\.tsx?$/,
          exclude: /node_modules/
        },
      ]
   },
}

8.运行命令 npm run dev

9.项目的目录结构为

10.将代码发送到仓库

git add .
git commit -m '[feature]js-to-ts'
git push

以上内容如有遗漏错误,欢迎留言 ✍️指出,一起进步💪💪💪

如果觉得本文对你有帮助,🏀🏀留下你宝贵的 👍


上一篇: webpack启动本地服务到加载vue文件

下一篇: vue中引入ts代码