適用于MacOS丽声,在Windows下也可以用類似思路實(shí)現(xiàn)乎澄。
首先確認(rèn)你已經(jīng)安裝了nodejs和npm命令行工具。
創(chuàng)建CreateWebProject.sh
文件螃宙,復(fù)制粘貼下面代碼然后保存蛮瞄,終端修改為可執(zhí)行權(quán)限chmod +x CreateWebProject.sh
,運(yùn)行它sh CreateWebProject.sh
谆扎,隨意輸入項(xiàng)目文件夾名稱挂捅,等待網(wǎng)頁打開,編輯src/index.js
保存堂湖,網(wǎng)頁會實(shí)時更新闲先。推薦使用VSCode編輯。
#!/bin/bash
# 需要修改為可執(zhí)行文件 chmod +x CreateWebProject.sh
# 然后 sh CreateWebProject.sh
#!/bin/bash
# 切換阿里云npm鏡像
npm config set registry https://registry.npmmirror.com
npm config get registry
#!/bin/bash
# 提示用戶輸入項(xiàng)目名稱
read -p "請輸入項(xiàng)目名稱: " project_name
# 檢查用戶是否輸入了項(xiàng)目名稱
if [ -z "$project_name" ]; then
echo "項(xiàng)目名稱不能為空无蜂。"
exit 1
fi
# 創(chuàng)建項(xiàng)目目錄并進(jìn)入
mkdir "$project_name" && cd "$project_name"
# 初始化 npm 項(xiàng)目
npm init -y
# 安裝開發(fā)所需的依賴
npm install --save-dev @babel/core @babel/cli @babel/preset-env webpack webpack-cli webpack-dev-server babel-loader html-webpack-plugin
# 創(chuàng)建 Babel 配置文件
echo '{
"presets": ["@babel/preset-env"]
}' > .babelrc
# 創(chuàng)建 Webpack 配置文件
echo 'const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
clean: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
],
devServer: {
static: {
directory: path.join(__dirname, "dist"),
},
compress: true,
port: 8080,
open: true, // 自動打開瀏覽器
client: {
logging: "error", // 禁用客戶端日志
},
devMiddleware: {
stats: "errors-only", // 只輸出錯誤信息
},
},
mode: "development",
};' > webpack.config.js
# 創(chuàng)建項(xiàng)目結(jié)構(gòu)
mkdir src
echo 'const greet = () => {
const hellostr = `Hello ES6!`
const root = document.getElementById(`root`)
root.innerHTML = `<h1>${hellostr}</h1><p>${new Date()}</p>`
console.log(hellostr)
}
greet()' > src/index.js
echo '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES6 Project</title>
</head>
<body>
<div id="root"></div>
<script src="bundle.js"></script>
</body>
</html>' > src/index.html
# 添加構(gòu)建和啟動腳本到 package.json
npx json -I -f package.json -e 'this.scripts={"build":"webpack","dev":"webpack serve --open"}'
# 構(gòu)建項(xiàng)目
npm run build
# 輸出訪問地址
echo "\n你的項(xiàng)目已經(jīng)啟動伺糠,可以在瀏覽器中訪問 http://localhost:8080"
# 啟動開發(fā)服務(wù)器
npm run dev
END