分类目录归档:其他

基于vue-cli4的多页面构建配置

vue.config.js

<code class="language-null">const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
var fs = require('fs');
const CopyPlugin = require('copy-webpack-plugin');
let init_path = process.env.VUE_APP_BUILD_PATH;
let relative_path = init_path;
if (!/^(\.|\/)/.test(init_path)) {
  //补齐相对路径
  relative_path = `./${init_path}`;
}
if (!/\/$/.test(init_path)) {
  //补齐目录斜线
  relative_path = `${relative_path}/`;
}
let entry_path = `${relative_path}**/*.html`;
//配置pages多页面获取当前文件夹下的html和js
function getEntry(globPath) {
  let entries = {},
    basename,
    arr,
    tmp,
    pathname,
    appname;

  glob.sync(globPath).forEach(function(entry) {
    basename = path.basename(entry, path.extname(entry));
    arr = entry.split('/');
    tmp = arr.splice(1, arr.length - 2);
    pathname = basename; // 正确输出js和html的路径
    pagename = basename + '.html';

    entries[pathname] = {
      entry: tmp.join('/') + '/' + basename + '.js',
      template: tmp.join('/') + '/' + pagename,
      title: pagename,
      filename: pagename
    };
  });
  return entries;
}

let pages = getEntry(entry_path);
let event_id = process.env.EVENT_ID;
let is_production = process.env.NODE_ENV == 'production';

//HTML文件输出路径是对的,资源文件路径是错的
let assetsDir = is_production ? `v2/${event_id}/` : `res_dev/`; 
let publicPath = is_production ? '//xxx.com/page/' : '/'

//资源文件路径是对的,HTML文件输出路径是错的

let AddAssetHtmlPluginPath = is_production ? `//xxx.com/page/` : ``;

function getMockDataCb(file){
  return function(req, res){
    let mockData = JSON.parse(fs.readFileSync(`./mock${file}`, 'utf8'));
    res.json(mockData);
  }
};

module.exports = {
  outputDir: `../htdocs/page/`,  //当运行 vue-cli-service build 时生成的生产环境构建文件的目录
  assetsDir: assetsDir, //放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录; serve和build构建都会生效,所以要区分环境
  // indexPath: ``, //指定生成的 index.html 的输出路径 (相对于 outputDir)。也可以是一个绝对路径
  publicPath: publicPath,
  pages,
  devServer: {
    before(app){
      let mockList = glob.sync('./mock/**/*.json').map((item, index) =&gt; {
        return item.replace(/^\.\/mock/, '');
      });
      console.log(mockList)
      mockList.forEach((file, index) =&gt; {
        app.get(file, getMockDataCb(file))
      });
    }
  },
  chainWebpack: config =&gt; {
    config.resolve.alias.set('@', path.resolve(__dirname, './'));
  },
  configureWebpack: config =&gt; {
      let pluginsPro = [
      new webpack.DllReferencePlugin({
        // context: process.cwd(),
        manifest: require('../htdocs/res/vendor/lib-manifest.json')
      })
      ,new webpack.DllReferencePlugin({
        // context: process.cwd(),
        manifest: require('../htdocs/res/vendor/global-manifest.json')
      })
      ,// 将 dll 注入到 生成的 html 模板中
      // ,new HtmlWebpackPlugin()
      new AddAssetHtmlPlugin({
        // dll文件位置
        filepath: path.resolve(__dirname, '../htdocs/res/vendor/*.js'),
        // dll 引用路径
        publicPath: AddAssetHtmlPluginPath,
        // dll最终输出的目录
        outputPath: AddAssetHtmlPluginPath
      })
    ];
    let productPlugins = [
      new CopyPlugin([
        {
          // from: `../htdocs/page/v2/${event_id}/**/*`,
          from: path.resolve(__dirname, `../htdocs/page/v2/${event_id}`)+'/**/*',
          // to: `../htdocs/res/v2/${event_id}/`,
          to: path.resolve(__dirname, `../htdocs/res/v2/${event_id}`),
          force: true,
          toType: 'dir',
          transformPath(targetPath, absolutePath) {
            return targetPath.replace(`htdocs\\page\\v2\\`, '');
          }
        }
      ])
    ];

    if (process.env.NODE_ENV === 'production') {
      // 为生产环境修改配置
      pluginsPro = pluginsPro.concat(productPlugins);
    } else {
      // 为开发环境修改配置
    }
    config.plugins = [...config.plugins, ...pluginsPro];
  }
};
</code>

webpack.dll.conf.js

<code class="language-null">const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// dll文件存放的目录
const dllPath = '../htdocs/res/vendor';
module.exports = {
  entry: {
    lib: ['vue', 'core-js', 'axios'],
    global: ['zepto', '@/global/flexible.js', '@/global/index.js']
  },
  output: {
    path: path.resolve(__dirname, dllPath),
    filename: '[name].dll.[contenthash].js',
    library: '[name]_dll'
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './')
    }
  },
  module: {
    rules: [{
      test: require.resolve('zepto'),
      loader: 'exports-loader?window.Zepto!script-loader'
    }]
  },
  plugins: [
      //清除之前的dll文件
      new CleanWebpackPlugin(),
      //设置环境变量
      new webpack.DefinePlugin({
          'process.env': {
              NODE_ENV: 'production'
          }
      }),
      //manifest.json描述动态链接库包含了哪些内容
      new webpack.DllPlugin({
          path: path.join(__dirname, dllPath, '[name]-manifest.json'),
          name: '[name]_dll',
          context: process.cwd()
      })
  ]
};
</code>

vue全局ui插件

前言

参照element的方式,写了个简单vue全局ui插件的代码基本组织结构,已经剥离了大部分非关键代码,应该可以一看就懂。

入口js

<code class="language-null">import Vue from 'vue'
import App from './index.vue'
import AuthUi from '@/global/authui.js'

Vue.use(AuthUi);

new Vue({
  render: h =&gt; h(App),
}).$mount('#app')
</code>

插件汇总js @/global/authui.js

<code class="language-null">//参考 https://github.com/ElemeFE/element/blob/dev/src/index.js
import Tips from '@/module/tips/1.0.0/index.js'

const components = [
    Tips
];

const install = function(Vue) {
    components.forEach(component =&gt; {
      Vue.component(component.name, component);
    });

    Vue.prototype.$tips = Tips;

};

/* istanbul ignore if */
if (typeof window !== 'undefined' &amp;&amp; window.Vue) {
    install(window.Vue);
}

export default {
      install,
      Tips
}
</code>

组件入口js @/module/tips/1.0.0/index.js

<code class="language-null">//参考 https://github.com/ElemeFE/element/blob/dev/packages/message/src/main.js
import Vue from 'vue';
import Main from './main.vue';

let TipsConstructor = Vue.extend(Main);

let instance;
let seed = 1;

const Tips = function(options){
    if (typeof options === 'string') {
        options = {
            message: options
        };
    }
    let userOnClose = options.onClose;
    let id = 'tips_' + seed++;
    options.onClose = function(){
        Tips.close(id, userOnClose);
    };
    instance = new TipsConstructor({
        data: options
    });
    instance.id = id;
    instance.$mount();
    document.body.appendChild(instance.$el);
    return instance;
}

export default Tips
</code>

组件模板 @/module/tips/1.0.0/main.vue

<code class="language-null">&lt;template&gt;
&lt;div class="msg-mode"&gt;
    &lt;div class="msg-text text-center"&gt;tips text {{message}}&lt;/div&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
    name: 'Tips',
    data(){
        return {
            message: ''
        }
    },
    mounted(){

    }
}
&lt;/script&gt;
&lt;style lang="less" scoped&gt;

&lt;/style&gt;
</code>

我的折腾list

之前做的东西,有时间没看都快忘了,整理下,方便以后查找。

1、2048朝代版,还可以手机上玩

http://realwall.cn/ts/2048/canvas.html

2、弹性小球动画,一对好基友欢乐的跳来跳去

http://realwall.cn/ts/ball/ball.html

3、弹性小球动画升级版——推球,这个需要在手机上玩,因为只绑了touch事件,没有处理mouse事件。

http://realwall.cn/ts/ball/pushball/ball.html

4、弹性小球再升级——多终端推球小游戏,这个游戏由于需要与服务器端建立websocket连接,需要我启动服务才行。

http://realwall.cn:3000/

5、雪天跑步的人动画,虽然丑的不忍直视,但是毕竟动起来了~

http://realwall.cn/ts/snow_man/index.html

6、变色画板,在手机上打开,选中某一区域可以看到变色效果

http://realwall.cn/ts/draw/index.html

MATLAB读写视频文件

做视频实验最基本的就是视频的读写操作了,写了两个简单的函数来读写视频。

读视频函数readVideo输入读取文件的路径+文件名,输出帧结构数组,用官方的话说就是 Array of frame structures, each of which contains fields cdata and colormap.

%// read vedio
function source = readVideo(filePath)
readerobj = VideoReader(filePath);

%// Read in all video frames.
vidFrames = read(readerobj);

%// Get the number of frames.
% numFrames = get(readerobj, 'NumberOfFrames');
[d1, d2, d3, d4] = size(vidFrames);

%// Create a MATLAB movie struct from the video frames.
for k = 1 : d4
     source(k).cdata = vidFrames(:,:,:,k);
     source(k).colormap = [];
end

写视频函数,cutVideo截取源视频的某部分,写到目标路径,写入的视频格式为avi

%// cut and write video file 
%// srcFile can be avi or mpg, destFile to be avi
function cv = cutVideo(srcFile, destFile, startIndex, endIndex)

source = readVideo(srcFile);
source2 = source(startIndex:endIndex);
writerObj = VideoWriter(destFile);
open(writerObj);
writeVideo(writerObj,source2);
close(writerObj);

cv = source2;

 

参考文章:

http://www.mathworks.cn/cn/help/matlab/ref/videowriter.writevideo.html