安裝node-sass
1 2 3 4
| $ npm init
$ npm install node-sass --save-dev
|
建立資料夾scss 及 main.scss
創建main.scss
1 2 3 4
| $ mkdir sass $ cd sass/ $ touch main.scss
|
在package.json編寫compile腳本
開啟package.json, 在”scripts”那欄依序輸入: {"腳本名稱": "node-sass 來源檔 目的檔"}
, 這是我們建立的腳本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| { "name": "mahoshojo", "version": "1.0.0", "description": "Landing page for mahoshojo", "main": "index.js", "scripts": { "compile:sass": "node-sass app/sass/main.scss app/css/style.css" }, "author": "QB9487", "license": "ISC", "devDependencies": { "node-sass": "^4.11.0" }, "dependencies": { "jquery": "^3.3.1" } }
|
在terminal執行腳本
1 2 3 4 5 6 7
| $ npm run compile:sass
> mahoshojo@1.0.0 compile:sass D:\Sites\1-Mahoshojo > node-sass app/sass/main.scss app/css/style.css
Rendering Complete, saving .css file... Wrote CSS to D:\Sites\1-Mahoshojo\app\css\style.css
|
開啟 app\css\style.css
, 可以看到main.scss的內容, 被轉譯後寫入style.css
1 2 3 4 5 6 7 8
| .header { height: 95vh; background-image: linear-gradient(to right bottom, rgba(255, 153, 221, 0.7), rgba(150, 16, 94, 0.7)), url(../img/pink.jpg); background-size: cover; background-position: top; position: relative; clip-path: polygon(0 0, 100% 0, 100% 75vh, 0 100%); }
|
加入自動監看指令: -w
在腳本設定後加 -w
代表watch
1 2 3
| "scripts": { "compile:sass": "node-sass app/sass/main.scss app/css/style.css -w" },
|
執行腳本時, 附加指令 -w
, 每當main.scss
存檔時, 腳本就會自動將其轉譯寫入style.css
1 2 3 4 5 6 7 8 9 10
| $ npm run compile:sass -w
> mahoshojo@1.0.0 compile:sass D:\Sites\1-Mahoshojo > node-sass app/sass/main.scss app/css/style.css -w
=> changed: D:\Sites\1-Mahoshojo\app\sass\main.scss Rendering Complete, saving .css file... Wrote CSS to D:\Sites\1-Mahoshojo\app\css\style.css
|
註: 基本上這個功能和gulp watch是類似的, 但寫起來比gulp watch方便多了。
在全域安裝 Live server
1 2 3 4 5 6 7 8 9
| $ npm install live-server -g
$ sudo npm install live-server -g
$ live-server -v live-server 1.2.1
|
執行live-server
1 2 3 4
| $ live-server Serving "D:\Sites\1-Mahoshojo" at http://127.0.0.1:8080 Ready for changes GET /favicon.ico 404 3.359 ms - 150
|
同時使用live-server及node-sass
目前我們能夠使用兩個package:
- node-sass ==> 自動轉譯SCSS檔
- live-server ==> 自動更新頁面
在有package.json的資料夾中執行node-sass:
1
| $ npm run compile:sass -w
|
在有index.html的資料夾中執行live-server:
這兩者記得同時在兩個terminal開啟, 並且不要關掉, 其效果是, 每當我們儲存main.scss, 網頁就會自動更新成修改後的樣貌.