針對 webpack 安裝與編譯環境建置說明。
安裝 npm
安裝 nodejs
就可以使用 npm
工具。
下載 TLS 版本安裝。
安裝 yarn
yarn
是一套跟 npm
類似個套件安裝工具,但是速度比起 npm
快上許多。
下載 Stable 版本安裝。
初始化專案
cd vue
yarn init -y
建立一個資料夾,這邊使用 vue
來當專案資料夾,使用 yarn init -y
來初始化專案
使用 -y
就不會問你相關設定問題。
執行完畢後會產生一個 package.json
來記錄相關資訊。
安裝 webpack
yarn add webpack
yarn add webpack-cli
建立指令
編輯 package.json
,加入
"scripts": {
"test": "echo Error: no test specified && exit 1",
"build": "webpack"
},
專案目錄建立
- 建立一個
dist
資料夾,對外呈現的內容放這邊。 - 建立一個
src
資料夾,開發的檔案放這邊。
目前的目錄架構應該長這樣。

建立編譯檔案
- 建立
dist/index.html
,輸入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
<script src="main.js"></script>
</html>
- 建立
src/index.js
,輸入
import Vue from 'vue'
new Vue({
el: '#app',
mounted() {
console.log('Hello Webpack and Vue !');
}
});
安裝 vue 套件
yarn add vue
編譯
yarn run build
開啟瀏覽器查看,沒有錯誤且有順利印出 Hello Webpack and Vue !
表示成功。
安裝 Babel 相依套件
yarn add babel-core babel-loader
yarn add babel-preset-env babel-preset-vue
安裝 vue 編譯套件
yarn add vue-loader vue-style-loader css-loader file-loader vue-template-compiler
babel-loader 新版本編譯有問題
打開 package.json
"babel-loader": "^8.0.6", => "babel-loader": "^7.1.5",
將 node_modules
資料夾砍掉,執行 yarn install
重新安裝套件。
建立 webpack 設定檔
在安裝目錄下建立檔案 webpack.config.js
const path = require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'development',
module: {
rules: [
{
test: /.vue$/,
loader: 'vue-loader'
},
// this will apply to both plain `.js` files
// AND `<script>` blocks in `.vue` files
{
test: /.js$/,
loader: 'babel-loader'
},
// this will apply to both plain `.css` files
// AND `<style>` blocks in `.vue` files
{
test: /.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},
{
test: /.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
plugins: [
// make sure to include the plugin for the magic
new VueLoaderPlugin()
],
resolve: {
alias: {
'vue': 'vue/dist/vue.js'
}
}
}
測試 vue component
建立 src/components/hello.vue
<template>
<div>Hello {{ name }}</div>
</template>
<script>
module.exports = {
data() {
return {
name: 'Vue Component!'
}
}
};
</script>
修改 src/index.js
import Vue from 'vue'
import hello from './components/hello.vue'
new Vue({
el: '#app',
mounted() {
console.log('Hello World');
},
components: { hello },
})
編譯指令
"scripts": {
"test": "echo Error: no test specified && exit 1",
"watch": "webpack --watch --mode development",
"prod": "webpack --mode production"
},