前端脚手架工程

113 阅读2分钟

一、基础结构处理

目录结构

.
├── build
│   ├── webpack.base.js # webpack公共配置
│   ├── webpack.dev.js  # webpack开发环境公共配置
│   └── webpack.prod.js # webpack生成环境公共配置
├── package.json
├── pnpm-lock.yaml
├── public
│   └── index.html
├── src
│   ├── App.vue
│   └── main.ts # 入口文件
└── tsconfig.json # ts配置

1. pnpm init 生成package.json文件

2. pnpm add webpack webpack-cli -D下载webpack和cli

3. pnpm add vue下载vue新版vue3

4. pnpm add typescript -D下载typescript

5. 创建tsconfig.json文件

{
    "compilerOptions": {
        "target": "ESNext",
        "module": "ESNext",
        "lib": ["ESNext", "DOM", "DOM.Iterable"],
        "skipLibCheck": true,
        "useDefineForClassFields": true,
        "moduleResolution": "Bundler",
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "noEmit": true,
        "allowImportingTsExtensions": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "strict": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noFallthroughCasesInSwitch": true   
    },
    "include": ["src/**/*.ts", "src/**/*.js", "src/**/*.d.ts", "src/**/*.vue"],
    "exclude": ["node_modules", "build", "dist"]
}

6. 创建public文件夹、src文件夹

截屏2024-08-25 下午3.29.59.png

src文件目录:

App.vue

<template>
    <div>
        <h2>hello webpack vue app</h2>
    </div>
</template>

<script setup lang="ts">
</script>

<style scoped>
</style>

main.ts

import { createApp } from 'vue';
import App from './App.vue';

createApp(App).mount('#app');

shims.vue.d.ts

declare module '*.vue' { 
    import type { DefineComponent } from 'vue'
    const component: DefineComponent<{}, {}, any>
    export default component
}

7. 下载webpack相关插件

pnpm add html-webpack-plugin -D 解析html模板

pnpm add vue-loader@17 -D vue3对应vue-loader版本

pnpm add ts-loader -D

pnpm add babel-loader @babel/core @babel/preset-env -D

pnpm add @babel/preset-typescript -D

8. 创建build文件夹

webpack.base.js

//webpack基本配置
//1.入口
//2.出口
//3.loader
//4.plugins

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');

/**
 * @type {import('webpack').Configuration}
 */
module.exports = {
  mode: 'development',
  entry: path.resolve(__dirname, '../src/main.ts'),
  output: {
    path: path.resolve(__dirname, '../dist'), // 打包后的目录
    filename: 'js/[name].[contenthash:6].js', // 打包后的文件名
    clean: true, // 清除上一次打包的文件
    publicPath: '/', // 打包后的资源的访问路径前缀
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, '../src'), // @ 代表 src 路径
      vue$: 'vue/dist/vue.runtime.esm-bundler.js', 
    },
    // 引入文件的时候不需要添加后缀,这个配置也会稍微的提升构建速度
    extensions:[".js", ".ts", ".vue", ".json"]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, '../public/index.html'),
      title: "Webpack Vue template"
    }),
    new VueLoaderPlugin() // vue-loader插件
  ],
  module: {
    rules: [
      {
        test: /\.m?jsx?$/,
        exclude: /node_modules/,
        use: 'babel-loader'
      },
      {
        test: /\.vue$/,
        use: 'vue-loader'
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true, // 关闭类型检测,即只进行转译
              appendTsSuffixTo: ['\\.vue$'] // 给vue文件添加ts后缀 
              // 单文件组件会被vue-loader解析成三个部分,script部分最终交给ts-loader去处理,tsc不知道如何处理.vue文件结尾的文件 会报错
              // vue 单文件组件中假如使用了lang="ts",ts-loader需要配置appendTsSuffixTo: [/\.vue$/],用来给.vue文件添加个.ts后缀用于编译。
            }
          },
          {
            loader: 'babel-loader',
            options: {
              presets: [
                [
                  "@babel/preset-typescript",
                  {
                    allExtensions: true // 支持所有文件扩展名 
                  }
                ]
              ]
            }
          }
        ]
      }
    ]
  }
}


9. 修改public index.html的title

<title><%= htmlWebpackPlugin.options.title %></title>

10. 打包测试

npx webpack -c build/webpack.base.js

二、babel相关处理

1、 babel基本预设配置

module.exports = {
  "presets": [
    [
      "@babel/preset-env",
    ],
  ]
}

2、 polyfill

pnpm add core-js regenerator-runtime

搭建应用建议配置:

module.exports = {
  presets: [
    [
      "@babel/preset-env",
      {
        useBuiltIns: "usage", // 或者entry
        corejs: 3
      }
    ]
  ],
}

由于会修改现有的全局对象:比如修改了Array、String的原型链等,因此搭建第三方库建议配置:

pnpm add @babel/runtime @babel/runtime-corejs3

pnpm add @babel/plugin-transform-runtime -D

module.exports = {
  "presets": [
    [
      "@babel/preset-env"
    ]
  ],
  "plugins": [
    [
      "@babel/plugin-transform-runtime",
      { "corejs": "3" }
    ]
  ]
}

3、浏览器版本目标

按需配置browserslistrc:

.browserslistrc默认值是

> 0.5%, last 2 versions, Firefox ESR, not dead

可以自定义:创建一个.browserslistrc文件

> 1%
last 3 versions
not ie <= 11

4、修改webpack的配置

将之前的typescript的预设,直接提取到babel的配置文件中

// babel.config.js
module.exports = {
  presets: [
    [
      "@babel/preset-env",
      {
        useBuiltIns: "usage",
        corejs: 3
      }
    ],
    [
      "@babel/preset-typescript",
      {
        allExtensions: true
      }
    ]
  ],
  // plugins: [
  //   [
  //     "@babel/plugin-transform-runtime",
  //     { "corejs": "3" }
  //   ]
  // ]
}