requirejs 使用实例r.js打包

时间:2022-10-13 03:44:44

在这里,请先看基础文章与相关技术文档:

  1. 安装:
    npm init
    npm install requirejs
    --save
    npm install jquery@
    1.11.1 --save

    创建基本目录:
    js
    /main.js&test.js
    css/index.css
    index.html
    build.js
    copy requirejs目录下的r.js到根目录


    创建导出目录:one

    测试目录创建完成!
  2. index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/index.css">
    </head>
    <body>
    <iframe class="iframe" src="http://baidu.com" frameborder="0" height="300"></iframe>

    <script type="text/javascript" defer anync="true" src="node_modules/requirejs/require.js" data-main="js/main"></script>
    </body>
    </html>
  3. build.js
    //参考配置目录  http://www.yfznw.com/node/22
    ({ dir:
    './one',//输出路径
    paths:{
    jquery:
    'node_modules/jquery/dist/jquery.min',
    test:
    'js/test',
    index:
    'css/index.css'
    },
    name:
    'js/main',// 模块入口
    optimize: 'none',//是否压缩 默认是压缩的,去掉不要就是压缩
    })
  4. main.js
    require.config({
    baseUrl:
    'node_modules/',
    paths:{
    'jquery':'jquery/dist/jquery.min',
    'js':'../js'
    }
    });
    require([
    'jquery','js/test'],function($,test) {
    console.log($);
    test.one();
    });
  5. test.js
    define([],function() {
    var testing = {};

    testing.one
    = function() {
    console.log(
    'module testing');
    };

    return testing
    });
  6. index.css (主要只是存在而己,设定了流动条样式)
    @charset "utf-8";

    *::-webkit-scrollbar
    {width:2px;height:12px;}
    *::-webkit-scrollbar-button:start:decrement, ::-webkit-scrollbar-button:end:increment
    {width:0;height:0;}
    *::-webkit-scrollbar-button:vertical:increment
    {background:transparent;}
    *::-webkit-scrollbar-track-piece:vertical
    {background:#DFE7EF;}
    *::-webkit-scrollbar-track-piece:vertical:hover
    {background:#DFE7EF;}
    *::-webkit-scrollbar-track-piece:horizontal
    {background-color:transparent;}
    *::-webkit-scrollbar-thumb:vertical
    {height:100px;background:rgba(110,146,182,.5);}
    *::-webkit-scrollbar-thumb:vertical:hover
    {background:rgba(110,146,182,.4);}
    *::-webkit-scrollbar-thumb:horizontal
    {width:80px;height:10px;background-color:#ccc;}
  7. 目录截图
    requirejs 使用实例r.js打包

     

  8. 生成r.js打包目录
    //切换到根目录

    执行:node r.js
    -o build.js

     

  9. 效果:
    新目录one就是一个新的站点,那么流程到此结束;可看到与未打包时一样的结果;但是,相对而言请求被打包了,文件被打包了,那么还有更多 的细节,请查看官方文档