面试官:Vue3的webpack环境如何搭建?
思考一分钟
最近笔者正在学习 Vue3 ,想了解一下它的新语法和新特性。于是想从搭建 Vue3 + webpack 的开发环境开始学起,虽记录之,以便日后学习之用。
废话不多说,正文开始!
创建目录
在你喜欢的位置创建一个文件夹:
mkdir vue3-learning
cd vue3-learning
初始化项目
简单初始化一哈 package.json:
npm init -y
安装 webpack
npm i webpack webpack-cli webpack-dev-server -D
安装 html-webpack-plugin
npm i html-webpack-plugin -D
安装 vue3
npm i vue@next -S
npm i @vue/compiler-sfc@3.0.0-rc.9 vue-loader@16.0.0-alpha.3 -D
webpack.config.js
根目录添加之,再用你单身20多年的双手添加如下配置:
const path = require("path")
const htmlWebpackPlugin = require("html-webpack-plugin")
const { VueLoaderPlugin } = require("vue-loader")
module.exports = {
entry: {
app: "./src/index.js",
},
output: {
filename: "js/[name].bundle.js",
path: path.resolve(__dirname, "dist"),
},
devtool: "inline-source-map",
devServer: {
contentBase: "./dist",
},
module: {
rules: [
{
test: /\.vue$/,
use: ["vue-loader"],
},
],
},
plugins: [
new VueLoaderPlugin(),
new htmlWebpackPlugin({
template: "index.html",
}),
],
}
项目结构
此时项目的目录结构如下:
vue3-learning
|- src
|- app.vue
|- index.js
|- index.html
|- package.json
|- package-lock.json
|- webpack.config.js
index.js
入口文件中添加如下内容:
import { createApp } from "vue"
import App from "./app.vue"
createApp(App).mount("#app")
app.vue
根组件实例中添加如下内容:
<template>
<div id="app">{{ message }}</div>
</template>
<script>
import { ref } from "vue"
export default {
setup() {
const message = ref("hello, Vue3!")
return {
message,
}
},
}
</script>
命令行
在 package.json 添加启动命令行:
{
...
"scripts": {
"dev": "webpack-dev-server --color --open"
},
...
}
运行它!
npm run dev # Project is running at http://localhost:8080/
你可以狠狠的戳这里查看源码!后续 vue3 全家桶也会陆续跟进,敬请关注!
enjoy it~
参考资料
最后
写的不对的地方,欢迎斧正,谢谢!