gulp之index.html的拆解与组装

来源:互联网 发布:js frameelement.api 编辑:程序博客网 时间:2024/04/30 15:20

本篇文章是基于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.");})