# 前端變量 variable ### style > demo.css ~~~css :root { --w: 210; } @media screen and (orientation: portrait) { --w: 170; } #box { width: calc(var(--w) * 1px); } ~~~ > demo.scss ~~~scss :root { --w: 210; } $h: 180; //for scss/sass #box { --w: 210; width: calc(var(--w) * 1px); height: $h + 'px'; @media (orientation: portrait) { --w: 170; $h: 145; height: $h + 'px'; } } ~~~ ### pugjs/pug > meta.pug ~~~pugjs head meta(charset="utf-8")/ if ogtitle!=="" title=ogtitle link(href="css/" + papers + ".css" rel="stylesheet" type="text/css") ~~~ > index.pug ~~~pugjs - var papers = "index"; - var ogtitle = "首頁"; doctype html html(lang="zh-TW") include inc/meta.pug ='\n' body ... ~~~ ### gulp > gulpfile.babel.js ~~~javascript /* 清除 */ export function clean() { return del(["./.tmp", "./dist/"]) }; /* 變數 */ var envOptions = { string: "env", default: { env: "develop" } }; var options = minimist(process.argv.slice(2), envOptions); var envIsPro = options.env === "production" || options.env == "pro"; var isDev = process.argv.slice(2)[0] !== "build"; const pugOption = { 'pug_isDc': false, 'pug_baseUrl': 'https://dc.udn.com', 'gulp_env': isDev ? '開發中' : '上線輸出', 'gulp_fbappid': 123456789 } console.log(pugOption.gulp_env); /* 預處理 */ export function pugToHtml() { return gulp .src(['pug/demo.pug']) .pipe( $.pug({ pretty: true, //格式化 locals: pugOption }) ) .pipe(gulp.dest('./dist/')) }; /* 監聽 */ export function watch() { gulp.watch(["pug/**"], pugToHtml); }; /* 指令 */ exports.default = gulp.series( cb => { pugOption.pug_baseUrl = 'http://localhost:8080'; //輸出變更 envIsPro = false; //輸出變更 cb() }, gulp.parallel( pugToHtml, watch ) ); exports.build = gulp.series( cb => { pugOption.pug_isDc = true; //輸出變更 envIsPro = true //輸出變更 cb() }, gulp.series(clean), gulp.parallel(pugToHtml) ); ~~~ > demo.pug ~~~pugjs - var fbappid = gulp_fbappid; body #fb-root script. window.fbAsyncInit = function() { FB.init({ appId : #{fbappid}, autoLogAppEvents : true, xfbml : true, version : 'v10.0' }); }; ~~~ ### webpack > webpack.config.js ~~~javascript module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, mode: "production", module: { rules: [ { test: /\.s[ac]ss$/, //正規表達式 use: [ "css-loader", // "sass-loader" { loader: 'sass-loader', options: { additionalData: '$imgsrc: "https://pgw.udn.com.tw/..."', }, }, ] } ] }, }; ~~~ > demo.scss ~~~scss #box { --bg-img: url('#{$imgsrc}static/images/desktop.jpg'); background-image: var(--bg-img); @media (orientation: portrait) { --bg-img: url('#{$imgsrc}static/images/mobile.jpg') /* background-image: url($imgsrc + 'static/images/mobile.jpg'); */ } } ~~~