徒手搭建VUE3项目(一):webpack初始化

创建一个空文件夹,进入,运行脚本
	yarn init -y

-y可以跳过步骤,后期可以直接在package.json里面修改

安装webpack相关依赖
	yarn add webpack webpack-dev-server webpack-merge webpack-cli

其中webpack-dev-serverwebpack-cli启动本地服务,webpack-merge用于合并配置文件,下面有用到

安装vue相关依赖
	yarn add vue@next vue-loader@next @vue/compiler-sfc

@next安装最新版本,vue-loader负责将.vue文件转换为.html .js .css等,而vue-loader在版本16后就不再支持vue-template-compiler,转而使用@vue/compiler-sfc来解析template->render

安装css依赖,支持less
	yarn add css-loader style-loader less less-loader

css-loader处理js中通过import/require() @import / url引入的css文件,而style-loader处理js中的style标签的样式

安装ts依赖
	yarn add typescript ts-loader

ts必须有个显式的配置文件,在根目录下创建tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    // 这样就可以对 `this` 上的数据属性进行更严格的推断
    "strict": true,
    "jsx": "preserve",
    "moduleResolution": "node"
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.vue",
    "src/**/*.js",
  ],
  "exclude": [
    "node_modules"
  ]
}
webpack配置

根目录下创建webpack.config.js

//webpack.config.js
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const {
    VueLoaderPlugin
} = require("vue-loader");

module.exports = {
    entry: "./src/main.ts",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "js/[name].[hash:8].js"
    },
    // 启动服务
    devServer: { 
        hot: true, // 热模块替换
        port: "3000",
        // open: true, // 启动后打开浏览器
    },
    module: {
        rules: [{
                test: /\.vue$/,
                use: "vue-loader"
            },
            {
                test: /\.(css|less)$/,
                use: [{
                    loader: "style-loader"
                }, {
                    loader: "css-loader"
                }, {
                    loader: "less-loader",
                    options: {
                        lessOptions: {
                            javascriptEnabled: true // 允许链式调用
                        }
                    }
                }]
            },
            {
                test: /\.(t|j)s$/,
                exclude: /node_modules/,
                use: {
                    loader: "ts-loader",
                    options: {
                        configFile: path.resolve(__dirname, "tsconfig.json"), // 指定ts的配置文件
                        // 对应文件添加个.ts或.tsx后缀
                        appendTsSuffixTo: [/\.vue$/],
                        transpileOnly: true, // ? 关闭类型检查,即只进行转译
                    }
                }
            },
            {
                test: /\.(png|jpg|jepg|gif)$/,
                use: {
                    loader: "url-loader",
                    options: {
                        limit: 5000,
                        name: "img/[name].[hash:8].[ext]"
                    }
                }
            }
        ],
    },
    resolve: {
    	// 别名
        alias: {
            "@": path.resolve(__dirname, "src"),
            "@hook": path.resolve(__dirname, "src/hooks"),
        },
        extensions: [".js", ".ts", ".vue"]
    },
    plugins: [
		// 将打包后的js加在index.html上
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, "./public/index.html")
        }),
        // 加载vue相关的配置规则
        new VueLoaderPlugin(),
        // new webpack.NamedModulesPlugin(),
        // new webpack.HotModuleReplacementPlugin(),
    ]
}
创建一个简单的vue项目
  1. 根目录下创建public文件夹,再创建index.html
  2. 创建src文件夹,创建app.vuemain.ts
//app.vue
<template>
    <h3>Hello world</h3>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
    setup() {},
});
</script>
<style lang="less">
</style>
// main.ts
import {
    createApp
} from "vue"
import App from "./app.vue"
const app = createApp(App);
app.mount("#app");

main.ts中会报错,不识别app.vue,此时在根目录下创建文件shims-vue.d.ts即可解决

// shims-vue.d.ts
declare module '*.vue' {
  import { defineComponent } from 'vue'
   const component: ReturnType<typeof defineComponent>
   export default component
 }
运行脚本和webpack环境变量
// package.json
{
	//....
	"scripts": {
	    "dev": "webpack-dev-server --config webpack.dev.js"
	},
	// ...
}

此处指定了配置文件从webpack.dev.js读取,为了实现开发和生产环境的区别对待,新增webpack.dev.js

const {
    merge
} = require("webpack-merge");
const webpack = require("webpack");
const webpackConfig = require("./webpack.config");
module.exports = merge(webpackConfig, {
    mode: "development",
    plugins: [
    	// 注入环境变量`PROCESS_ENV`,可在项目文件中直接使用
        new webpack.DefinePlugin({
            PROCESS_ENV: JSON.stringify("development") 
        })
    ]
})
运行
yarn run dev

运行成功。

补充

全部的依赖安装没有使用--save-dev,这个可以在生产阶段对webpack的优化中进行处理

持续更新…

你可能感兴趣的:(vue3,webpack,ts,webpack,vue,typescript)