先看看我的目錄結(jié)構(gòu)(我全局使用TS):
一、安裝配置webpack打包
安裝esno
npm install esno
esno 是基于 esbuild 的 TS/ESNext node 運行時,有了它,就可以直接通過esno *.ts的方式啟動腳本,package.json中添加 type:“module”,使用esm的模塊管理方式。
{
"name": "create-my-vue-test",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "esno ./config/build.ts"
},
"type": "module",
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"esno": "^4.0.0"
}
}
創(chuàng)建build.ts,執(zhí)行npm run build
安裝webpack、webpack-cli
npm install webpack
npm install webpack-cli
webpack必須安裝webpackcli
build.ts中編寫打包代碼
import webpack, { Stats } from "webpack";
import config from "./webpack.config"
//我直接使用webpack,不使用webpck-cli,vue的腳手架
const compiler = webpack(config, (err, stats) => {
if (err) {
console.error(err.stack || err)
} else if ((stats as Stats).hasErrors()) {
console.log(stats);
} else {
}
})
編寫打包配置文件webpack.config.ts
import path from "path";//nodejs里面的基本包,用來處理路徑
const parentDir = path.resolve(process.cwd());
//我們先打個基本的包
export default {
mode: "development" as "development",
entry: "./src/main.ts",
output: {
path: path.join(parentDir, 'dist'),
filename: "bundle.js",
},
module: {
// 指定要加載的規(guī)則
rules: [],
},
// 模塊配置:讓webpack了解哪些方法可以被當(dāng)作模塊引入
resolve: {
extensions: ['.ts', '.js']
},
plugins: []
};
創(chuàng)建業(yè)務(wù)代碼入口文件main.ts
let test: string = '';
console.log(test);
執(zhí)行一下打包npm run build
報錯了,說需要個loader來處理ts,我們安裝ts-loader,并在webpack.config.ts中添加相關(guān)配置
npm install ts-loader
import path from "path";//nodejs里面的基本包,用來處理路徑
const parentDir = path.resolve(process.cwd());
//我們先打個基本的包
export default {
mode: "development" as "development",
entry: "./src/main.ts",
output: {
path: path.join(parentDir, 'dist'),
filename: "bundle.js",
},
module: {
// 指定要加載的規(guī)則
rules: [
{
test: /\.ts$/, // 解析 ts
loader: "ts-loader"
}
],
},
// 模塊配置:讓webpack了解哪些方法可以被當(dāng)作模塊引入
resolve: {
extensions: ['.ts', '.js']
},
plugins: [
]
};
再次執(zhí)行npm run build
有報錯了,說沒有tsconfig.json文件
創(chuàng)建tsconfig.ts
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/*.ts",
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
再次打包,打包成功了
手動拷貝到index.html里面試試,運行也沒有問題
安裝HtmlWebpackPlugin自動拷貝打包文件到index.html中,安裝CleanWebpackPlugin,自動清除dist目錄,并更新webpack.config.ts
import path from "path";//nodejs里面的基本包,用來處理路徑
import { CleanWebpackPlugin } from "clean-webpack-plugin";
import HtmlWebpackPlugin from 'html-webpack-plugin';
const parentDir = path.resolve(process.cwd());
//我們先打個基本的包
export default {
mode: "development" as "development",
entry: "./src/main.ts",
output: {
path: path.join(parentDir, 'dist'),
filename: "bundle.js",
},
module: {
// 指定要加載的規(guī)則
rules: [
{
test: /\.ts$/, // 解析 ts
loader: "ts-loader"
}
],
},
// 模塊配置:讓webpack了解哪些方法可以被當(dāng)作模塊引入
resolve: {
extensions: ['.ts', '.js']
},
plugins: [
new HtmlWebpackPlugin({
title: '你好,世界',
template: './public/index.html'
}),
new CleanWebpackPlugin()
]
};
現(xiàn)在就可以自動將打包js文件插入到index.html中
增加開發(fā)服務(wù)并熱更新,安裝webpack-dev-server
npm install webpack-dev-server
創(chuàng)建dev.ts
import path from "path";//nodejs里面的基本包,用來處理路徑
import webpack, { Stats } from "webpack";
import WebpackDevServer from "webpack-dev-server";
import config from "./webpack.config"
const parentDir = path.resolve(process.cwd());
const compiler = webpack(config)
const server = new WebpackDevServer({
port: 3000,
static: {
directory: path.join(parentDir, 'public'),
},
}, compiler);
const runServer = async () => {
console.log('Starting server...');
await server.start();
};
runServer();
在package.json中增加dev的腳本
"scripts": {
"build": "esno ./config/build.ts",
"dev": "esno ./config/dev.ts"
},
執(zhí)行npm run dev
,就啟動起來了
二、集成Vue
增加App.vue、更改main.ts、main.scss
App.vue
<template>
<div>test</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
name: "App",
setup() {
return {};
},
});
</script>
main.ts
import { createApp } from 'vue'
import App from './components/App.vue'
import "./assets/main.scss"
// 注意:這里的 #app,需要在 public/index.html 中,寫一個 id 為 app 的 div
createApp(App).mount('#app');
main.scss
* {
background-color: red;
}
安裝依賴
npm i --save-dev vue vue-loader url-loader style-loader css-loader node-sass sass-loader
更改webpack.config.ts
import path from "path";//nodejs里面的基本包,用來處理路徑
import { CleanWebpackPlugin } from "clean-webpack-plugin";
import HtmlWebpackPlugin from 'html-webpack-plugin';
import { VueLoaderPlugin } from "vue-loader"
const parentDir = path.resolve(process.cwd());
//我們先打個基本的包
export default {
mode: "development" as "development",
entry: "./src/main.ts",
output: {
path: path.join(parentDir, 'dist'),
filename: "bundle.js",
},
module: {
// 指定要加載的規(guī)則
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
},
{
test: /\.scss$/,
use: [
'style-loader',//https://github.com/vuejs/vue-style-loader/issues/42
'css-loader',
'sass-loader'
]
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
name: './font/[hash].[ext]',
publicPath: 'dist'
}
}
]
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
},
},
],
},
{
test: /\.ts$/, // 解析 ts
loader: "ts-loader",
options: {
// 上面一行不太重要,應(yīng)該會按照默認(rèn)路徑尋找,下面一行必須要
// appendTsSuffixTo/appendTsxSuffixTo配置項的意思是說,從vue文件里面分離的script的ts,tsx(取決于<script lang="xxx"></script>)內(nèi)容將會被加上ts或者tsx的后綴,然后交由ts-loader解析。
// 我在翻看了ts-loader上關(guān)于appendTsxSuffixTo的討論發(fā)現(xiàn),ts-loader貌似對文件后綴名稱有很嚴(yán)格的限定,必須得是ts/tsx后綴,所以得在vue-loader extract <script>中內(nèi)容后,給其加上ts/tsx的后綴名,這樣ts-loader才會去處理這部分的內(nèi)容。
// 在Vue項目中使用Typescript
configFile: path.resolve(process.cwd(), 'tsconfig.json'),
appendTsSuffixTo: [/\.vue$/]
},
}
],
},
// 模塊配置:讓webpack了解哪些方法可以被當(dāng)作模塊引入
resolve: {
extensions: [
'.tsx',
'.ts',
'.mjs',
'.js',
'.jsx',
'.vue',
'.json']
},
plugins: [
new HtmlWebpackPlugin({
title: '你好,世界',
template: './public/index.html'
}),
new CleanWebpackPlugin(),
// make sure to include the plugin for the magic
new VueLoaderPlugin()
]
};
創(chuàng)建shims-vue.d.ts
/* eslint-disable */
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
最終的package.json文章來源:http://www.zghlxwxcb.cn/news/detail-817524.html
{
"name": "create-my-vue-test",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "esno ./config/dev.ts",
"build": "esno ./config/build.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.9.1",
"esno": "^4.0.0",
"html-webpack-plugin": "^5.6.0",
"node-sass": "^9.0.0",
"sass-loader": "^14.0.0",
"style-loader": "^3.3.4",
"ts-loader": "^9.5.1",
"url-loader": "^4.1.1",
"vue": "^3.4.15",
"vue-loader": "^17.4.2",
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
}
}
再次運行,基礎(chǔ)搭建好了文章來源地址http://www.zghlxwxcb.cn/news/detail-817524.html
到了這里,關(guān)于自己構(gòu)建webpack+vue3+ts的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!