本篇文章是基於gulp完成的項目
正常移動端項目中的index.html應該有的內容:
1.唯一的一個 .css 文件。(eg: app.css)
2.唯一的一個 .js 文件。(eg: app.js)
3.body中無內容標籤,使用 .string 的方式,通過js引入DOM元素。
PS:
app.css是由 app.scss 編譯而來的(基於sass)。app.scss 中也儘量是其他模塊寫好之後的 .scss 文件組裝用的。一般只放大體的樣式。
app.js 同上。(因爲這塊還未詳細瞭解,故先到這。)
下面是拆解與組裝的步驟:
1。將 index.html 中的內容抽出來(內容爲大體的頁面設計)。
2。將內容放到一個 .string 文件中。(index.string)
3。爲了能夠識別 .string 文件,需要引入 string-loader包
4。進入 npm 官網 : npmjs.org,搜索string-loader,瞭解詳情
5。npm i string-loader -D //下載string-loader包
6。在gulpfile.js文件中的webpack中添加loader
loaders: [
{
test: /\.string$/,
loader: 'string-loader', //所使用的loader,編譯.string文件的
}
]
7。使用 app.js 加載 index.string 文件到index.html 中
var str = require('../templates/index.string');
window.onload = function(){
var body = document.body;
body.innerHTML = str;
}
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></title>
<link rel="stylesheet" type="text/css" href="./styles/app.css"/>
</head>
<body>
<!--全局只需要引用一個css文件,一個js文件,其他的子文件通過css或js文件自己引用-->
<!--app.scss主要的作用是組合頁面上的各個部分的scss文件,用於生成一個完整的app.css文件-->
<!--body內不要裝DOM元素,使用.string 文件裝,然後在使用 js 加載。-->
</body>
<script src="scripts/app.js" type="text/javascript" charset="utf-8"></script>
</html>
index.string:
<div class="container">
<header>
</header>
<section>
<div class="m-position">
</div>
</section>
<footer>
</footer>
</div>
app.js:
var str = require('../templates/index.string');
window.onload = function(){
var body = document.body;
body.innerHTML = str;
}
gulpfile.js部分內容:
gulp.task('packjs', function () {
gulp.src('./src/scripts/app.js')
.pipe(named())
.pipe(webpack({
output: { //輸出
filename: '[name].js' //所輸出的文件名
},
module: { //使用loader將使用後臺語句的js文件編譯成瀏覽器能運行的語句
loaders: [
{
test: /\.js$/,
loader: 'imports-loader', //所使用的loader
exclude: './node_modules' //將node_modules中的js文件排除在外
}
],
loaders: [
{
test: /\.string$/,
loader: 'string-loader', //所使用的loader,編譯.string文件的
}
]
}
}))
.pipe(gulp.dest('./dev/scripts')) //將編譯後生成的js文件存放的位置
console.log("packjs.");
})