fex-team / fis3

FIS3
http://fis.baidu.com
BSD 2-Clause "Simplified" License
2.79k stars 694 forks source link

artTemplate 在 fis3中无法使用 #955

Open fukai007 opened 8 years ago

fukai007 commented 8 years ago

1、artTemplateJS 无法再fis3环境中使用 配置文件如下

/**
 *FIS3 config
 *@Author: miles.Fu;
 */

var PROJECT_NAME = "XXXXXXXXX";
var LOCAL_HOST_DOMAIN = "";
var PRODUCTION_DOMAIN = "";

var OUTPUT_DIR = "./output";

fis.config.set("project.watch.usePolling", true)
fis.set('project.charset', 'utf-8');
fis.set('project.md5Length', 8);
fis.set('project.md5Connector ', '_');
fis.set('project.ignore', [
  'node_modules/**',
  'output/**',
  'fis-conf*.js',
  'package.json',
  'bower_components/**',
  '/static/lib/artTemplate.js'
]);

fis.set('project.files', [
  "*.html",
  "*.js",
  "*.less",
  "*.jsx",
  "*.jpg",
  "*.jpeg",
  "*.png",
  "*.ssp",
  "*.jsp"
]);

fis.set('project.fileType.text', [ 'css', 'tpl', 'js', 'php',
'txt', 'json', 'xml', 'htm', 'text', 'xhtml',
 'html', 'md', 'conf', 'po', 'config', 'tmpl',
  'coffee', 'less', 'sass', 'jsp', 'ssp','scss', 'manifest',
  'bak', 'asp', 'tmp' ]);

//fis.hook('npm');
//模块化钩子 commonjs规则
fis.hook('commonjs', {});

fis.match("/static/lib/(lodash).js", {id: "$1",moduleId: "$1"});
fis.match("/static/lib/(jquery).js", {id: "$1",moduleId: "$1"});
fis.match("/static/lib/(underscore).js", {id: "$1",moduleId: "$1"});
fis.match("/static/lib/(template).js", {id: "$1",moduleId: "$1"});

//---------------------------------全局环境规则---开始--------------------------------
fis.match('*.less', {
  parser: fis.plugin('less'),
  preprocessor: function (content, file, settings) {
     console.log("---------------quan-ju---preprocessor--------------------");
  },
  postprocessor: fis.plugin('autoprefixer', {
      browsers: ["Android >= 2.3", "ChromeAndroid > 1%", "iOS >= 4", "Firefox >= 20", "last 2 versions"],
      cascade: true
    }),
  rExt: '.css'
}).match("*.{js,jsx}", {
  isMod: true,
  parser: ['babel'],
  rExt: 'js'
}).match('*.{js,css,png}', {
  //useHash: true
}).match("/pagelet/*/*.js",{
  // deploy: fis.plugin('local-deliver', {
  //   to: OUTPUT_DIR
  // })
}).match("**/mod.js", {
  isMod: false
}).match('/pages/*.html',{
    domain: LOCAL_HOST_DOMAIN,
    isHtmlLike : true,    //设置其为html文件模式,没起作用
    deploy: fis.plugin('local-deliver', {
      to: OUTPUT_DIR
    })
    //rExt: '.ssp'
});

// .match('*.png', {
//   // fis-optimizer-png-compressor 插件进行压缩,已内置
//   optimizer: fis.plugin('png-compressor')
// }).match('*.{scss,sass,less,css}', {
//   // fis-optimizer-png-compressor 插件进行压缩,已内置
//   optimizer: fis.plugin('clean-css',{
//       //option
//   })
// })
//
// .match("/static/lib/template.js",{
//
//     isMod: false
//})
//---------------------------------全局环境规则---结束--------------------------------

//---------------------------------开发环境规则---开始--------------------------------
var development = fis.media("debug");

//react .jsx 文件transfrom
development.match('::package', {
  postpackager: [fis.plugin('loader', {})]
});

development.match('*.{jsx,js,less,css,png,jpg,jpeg,svg,eot,ttf,woff}', {
  domain: LOCAL_HOST_DOMAIN,
  // preprocessor: function (content, file, settings) {
  //    console.log("---------------kai-fa---preprocessor--------------------");
  // },
  deploy: fis.plugin('local-deliver', {
    to: OUTPUT_DIR
  })
});
//---------------------------------开发环境规则---结束--------------------------------

使用代码如下 :

import $ from "jquery";
import template from "/static/lib/template";
//import _ from "lodash";
import _ from  "underscore";

var  t = {
      /*
         @fid  模板的父节点
         @tid  模板ID
         @templateType 选择模板的类型
         @data 数据
      */
      makeHtml :  function makeHtml(fid,tid,templateType,data){
          var htmlString = "";
          this.beforeMakeHtml.apply(this,arguments);
          switch(templateType){
              case "art":
                htmlString = this.artHtml(tid,data);
                break;

              case "lodash":
                htmlString = this.lodashHtml(tid,data);
                break;
              //默认使用 Underscore

              case "underscore":
                htmlString = this.underscoreHtml(tid,data);
                break;
              default:
                return "don't find template";
          }
          this.afterMakeHtml(fid,htmlString);
          document.getElementById(fid).innerHTML = htmlString;
      },

      /*
          eventObject : {
              eventType : ,
              domString :,
              fn :function(){} ,
              data :{}
          }
       */
      onEvent :  function onEvent(eventList,fid){
            var len = eventList.length;
            while (len--){
                var eo = eventList[len];
                var _fid = "#"+fid ;
                var _data = eo.data || {};
                // 绑定事件
                if(eo.domName || eo.domName == ""){
                  $( _fid ).on( eo.eventType,eo.domName,_data,eo.fn);
                }else{
                  $( _fid ).on(eo.eventType,_data,eo.fn);
                }
            }
      },
      /*
            artTemplate 模板引擎
       */
      artHtml : function artHtml(tid,data){
            return template(tid, data);
      },
      /*
            lodash 模板引擎
       */
      lodashHtml : function lodashHtml(tid,data){
            var compiled = _.template($("#"+tid).html());
            return compiled(data);
      },
      /*
            underscore 模板引擎
       */
      underscoreHtml : function underscoreHtml(tid,data){
            var compiled = _.template($("#"+tid).html());
            return compiled(data);
      },
      beforeMakeHtml : function beforeMakeHtml(){
            console.log(arguments);
      },
      afterMakeHtml : function afterMakeHtml(){
            console.log(arguments);
      }
}

var data = {
  title: '嵌入子模板',
  list: ['文艺', '博客', '摄影', '电影', '民谣', '旅行', '吉他']
};
var _d = {
    user : "miles...................."
}
t.makeHtml('content','test','art',data);
//t.makeHtml('content','und','underscore',_d);
//t.makeHtml('content','und','lodash',_d);
var el = [];
el.push({
    eventType : 'click',
    domName : 'li',
    fn : function fnc(evnet){
      console.log("-----------------------fnc.click is running....................");
    }
});
el.push({
    eventType : 'input',
    domName : '#bi',
    fn : function fni(event){
      console.log("-----------------------fni.input is running....................");
    }
});

el.push({
    eventType : 'change',
    domName : '#ss',
    fn : function fni(event){
      console.log("-----------------------fni.change is running....................");
    }
});

t.onEvent(el,'content');
2betop commented 8 years ago

有错误信息吗?光说有问题,但是没看到你对问题的描述。

2betop commented 8 years ago

关于 jsx 的 parser 改用这个插件试试

fis.match('*.jsx', {
  parser: fis.plugin('babel-5.x')
})
fukai007 commented 8 years ago

1、编译时不会报错 2、执行时会报错 Uncaught TypeError: (0 , _staticLibTemplate2.default) is not a function(…) 3、没用 react

fukai007 commented 8 years ago

FIS3 编译时打印出来的日志 : Ω .........[BABEL] Note: The code generator has deoptimised the styling of "/Users/fukai/testH5/test-two-html/static/lib/echarts.min.js" as it exceeds the max of "100KB". .[BABEL] Note: The code generator has deoptimised the styling of "/Users/fukai/testH5/test-two-html/static/lib/jquery.js" as it exceeds the max of "100KB". .[BABEL] Note: The code generator has deoptimised the styling of "/Users/fukai/testH5/test-two-html/static/lib/lodash.js" as it exceeds the max of "100KB". .........---------------quan-ju---preprocessor-1-------------------

[WARNI] invalid content return of pipe [preprocessor.0] ----------------quan-ju---preprocessor-2-------------------

[WARNI] invalid content return of pipe [preprocessor.1] ..---------------quan-ju---preprocessor-1-------------------

[WARNI] invalid content return of pipe [preprocessor.0] ----------------quan-ju---preprocessor-2-------------------

[WARNI] invalid content return of pipe [preprocessor.1] .---------------quan-ju---preprocessor-1-------------------

[WARNI] invalid content return of pipe [preprocessor.0] ----------------quan-ju---preprocessor-2-------------------

[WARNI] invalid content return of pipe [preprocessor.1] .---------------quan-ju---preprocessor-1-------------------

[WARNI] invalid content return of pipe [preprocessor.0] ----------------quan-ju---preprocessor-2-------------------

[WARNI] invalid content return of pipe [preprocessor.1] ....... 19.70s [14:49:11.153]

2betop commented 8 years ago

目测是 artTemplate 并没有暴露 default 方法,尝试改成

import * as template from "/static/lib/template";
fukai007 commented 8 years ago

这是它的源代码

/*!art-template - Template Engine | http://aui.github.com/artTemplate/*/
!function() {
    console.log(this);
    function a(a) {
        return a.replace(t, "").replace(u, ",").replace(v, "").replace(w, "").replace(x, "").split(y)
    }

    function b(a) {
        return "'" + a.replace(/('|\\)/g, "\\$1").replace(/\r/g, "\\r").replace(/\n/g, "\\n") + "'"
    }

    function c(c, d) {
        function e(a) {
            return m += a.split(/\n/).length - 1, k && (a = a.replace(/\s+/g, " ").replace(/<!--[\w\W]*?-->/g, "")), a && (a = s[1] + b(a) + s[2] + "\n"), a
        }

        function f(b) {
            var c = m;
            if (j ? b = j(b, d) : g && (b = b.replace(/\n/g, function() {
                    return m++, "$line=" + m + ";"
                })), 0 === b.indexOf("=")) {
                var e = l && !/^=[=#]/.test(b);
                if (b = b.replace(/^=[=#]?|[\s;]*$/g, ""), e) {
                    var f = b.replace(/\s*\([^\)]+\)/, "");
                    n[f] || /^(include|print)$/.test(f) || (b = "$escape(" + b + ")")
                } else b = "$string(" + b + ")";
                b = s[1] + b + s[2]
            }
            return g && (b = "$line=" + c + ";" + b), r(a(b), function(a) {
                if (a && !p[a]) {
                    var b;
                    b = "print" === a ? u : "include" === a ? v : n[a] ? "$utils." + a : o[a] ? "$helpers." + a : "$data." + a, w += a + "=" + b + ",", p[a] = !0
                }
            }), b + "\n"
        }
        var g = d.debug,
            h = d.openTag,
            i = d.closeTag,
            j = d.parser,
            k = d.compress,
            l = d.escape,
            m = 1,
            p = {
                $data: 1,
                $filename: 1,
                $utils: 1,
                $helpers: 1,
                $out: 1,
                $line: 1
            },
            q = "".trim,
            s = q ? ["$out='';", "$out+=", ";", "$out"] : ["$out=[];", "$out.push(", ");", "$out.join('')"],
            t = q ? "$out+=text;return $out;" : "$out.push(text);",
            u = "function(){var text=''.concat.apply('',arguments);" + t + "}",
            v = "function(filename,data){data=data||$data;var text=$utils.$include(filename,data,$filename);" + t + "}",
            w = "'use strict';var $utils=this,$helpers=$utils.$helpers," + (g ? "$line=0," : ""),
            x = s[0],
            y = "return new String(" + s[3] + ");";
        r(c.split(h), function(a) {
            a = a.split(i);
            var b = a[0],
                c = a[1];
            1 === a.length ? x += e(b) : (x += f(b), c && (x += e(c)))
        });
        var z = w + x + y;
        g && (z = "try{" + z + "}catch(e){throw {filename:$filename,name:'Render Error',message:e.message,line:$line,source:" + b(c) + ".split(/\\n/)[$line-1].replace(/^\\s+/,'')};}");
        try {
            var A = new Function("$data", "$filename", z);
            return A.prototype = n, A
        } catch (B) {
            throw B.temp = "function anonymous($data,$filename) {" + z + "}", B
        }
    }
    var d = function(a, b) {
        return "string" == typeof b ? q(b, {
            filename: a
        }) : g(a, b)
    };
    d.version = "3.0.0", d.config = function(a, b) {
        e[a] = b
    };
    var e = d.defaults = {
            openTag: "<%",
            closeTag: "%>",
            escape: !0,
            cache: !0,
            compress: !1,
            parser: null
        },
        f = d.cache = {};
    d.render = function(a, b) {
        return q(a, b)
    };
    var g = d.renderFile = function(a, b) {
        var c = d.get(a) || p({
            filename: a,
            name: "Render Error",
            message: "Template not found"
        });
        return b ? c(b) : c
    };
    d.get = function(a) {
        var b;
        if (f[a]) b = f[a];
        else if ("object" == typeof document) {
            var c = document.getElementById(a);
            if (c) {
                var d = (c.value || c.innerHTML).replace(/^\s*|\s*$/g, "");
                b = q(d, {
                    filename: a
                })
            }
        }
        return b
    };
    var h = function(a, b) {
            return "string" != typeof a && (b = typeof a, "number" === b ? a += "" : a = "function" === b ? h(a.call(a)) : ""), a
        },
        i = {
            "<": "&#60;",
            ">": "&#62;",
            '"': "&#34;",
            "'": "&#39;",
            "&": "&#38;"
        },
        j = function(a) {
            return i[a]
        },
        k = function(a) {
            return h(a).replace(/&(?![\w#]+;)|[<>"']/g, j)
        },
        l = Array.isArray || function(a) {
            return "[object Array]" === {}.toString.call(a)
        },
        m = function(a, b) {
            var c, d;
            if (l(a))
                for (c = 0, d = a.length; d > c; c++) b.call(a, a[c], c, a);
            else
                for (c in a) b.call(a, a[c], c)
        },
        n = d.utils = {
            $helpers: {},
            $include: g,
            $string: h,
            $escape: k,
            $each: m
        };
    d.helper = function(a, b) {
        o[a] = b
    };
    var o = d.helpers = n.$helpers;
    d.onerror = function(a) {
        var b = "Template Error\n\n";
        for (var c in a) b += "<" + c + ">\n" + a[c] + "\n\n";
        "object" == typeof console && console.error(b)
    };
    var p = function(a) {
            return d.onerror(a),
                function() {
                    return "{Template Error}"
                }
        },
        q = d.compile = function(a, b) {
            function d(c) {
                try {
                    return new i(c, h) + ""
                } catch (d) {
                    return b.debug ? p(d)() : (b.debug = !0, q(a, b)(c))
                }
            }
            b = b || {};
            for (var g in e) void 0 === b[g] && (b[g] = e[g]);
            var h = b.filename;
            try {
                var i = c(a, b)
            } catch (j) {
                return j.filename = h || "anonymous", j.name = "Syntax Error", p(j)
            }
            return d.prototype = i.prototype, d.toString = function() {
                return i.toString()
            }, h && b.cache && (f[h] = d), d
        },
        r = n.$each,
        s = "break,case,catch,continue,debugger,default,delete,do,else,false,finally,for,function,if,in,instanceof,new,null,return,switch,this,throw,true,try,typeof,var,void,while,with,abstract,boolean,byte,char,class,const,double,enum,export,extends,final,float,goto,implements,import,int,interface,long,native,package,private,protected,public,short,static,super,synchronized,throws,transient,volatile,arguments,let,yield,undefined",
        t = /\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|\s*\.\s*[$\w\.]+/g,
        u = /[^\w$]+/g,
        v = new RegExp(["\\b" + s.replace(/,/g, "\\b|\\b") + "\\b"].join("|"), "g"),
        w = /^\d[^,]*|,\d[^,]*/g,
        x = /^,+|,+$/g,
        y = /^$|,+/;
    e.openTag = "{{", e.closeTag = "}}";
    var z = function(a, b) {
        var c = b.split(":"),
            d = c.shift(),
            e = c.join(":") || "";
        return e && (e = ", " + e), "$helpers." + d + "(" + a + e + ")"
    };
    e.parser = function(a) {
        a = a.replace(/^\s/, "");
        var b = a.split(" "),
            c = b.shift(),
            e = b.join(" ");
        switch (c) {
            case "if":
                a = "if(" + e + "){";
                break;
            case "else":
                b = "if" === b.shift() ? " if(" + b.join(" ") + ")" : "", a = "}else" + b + "{";
                break;
            case "/if":
                a = "}";
                break;
            case "each":
                var f = b[0] || "$data",
                    g = b[1] || "as",
                    h = b[2] || "$value",
                    i = b[3] || "$index",
                    j = h + "," + i;
                "as" !== g && (f = "[]"), a = "$each(" + f + ",function(" + j + "){";
                break;
            case "/each":
                a = "});";
                break;
            case "echo":
                a = "print(" + e + ");";
                break;
            case "print":
            case "include":
                a = c + "(" + b.join(",") + ");";
                break;
            default:
                if (/^\s*\|\s*[\w\$]/.test(e)) {
                    var k = !0;
                    0 === a.indexOf("#") && (a = a.substr(1), k = !1);
                    for (var l = 0, m = a.split("|"), n = m.length, o = m[l++]; n > l; l++) o = z(o, m[l]);
                    a = (k ? "=" : "=#") + o
                } else a = d.helpers[c] ? "=#" + c + "(" + b.join(",") + ");" : "=" + a
        }
        return a
    }, "function" == typeof define ? define(function() {
        return d
    }) : "undefined" != typeof exports ? module.exports = d : this.template = d
  }();
fukai007 commented 8 years ago

已尝试 , 不行 ,您还有其他的解决方案吗? import * as template from "/static/lib/template";