webpack2.0+ vue2.0

一 webpack 2.0 及用到的插件安装(默认已经有node环境)

1. package.json文件 (插件安装及插件的功能不详解)

复制代码
{
  "private": true,
  "devDependencies": {
    "autoprefixer-loader": "^3.2.0",
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.7",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-stage-0": "^6.16.0",
    "babel-runtime": "^5.8.38",
    "clean-webpack-plugin": "^0.1.15",
    "css-loader": "^0.25.0",
    "debug": "^2.2.0",
    "express": "^4.14.0",
    "extract-text-webpack-plugin": "^2.0.0",
    "file-loader": "^0.9.0",
    "html-webpack-plugin": "^2.24.1",
    "node-sass": "^4.5.0",
    "postcss-loader": "^1.3.2",
    "sass-loader": "^6.0.2",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "vue-hot-reload-api": "^1.2.0",
    "vue-html-loader": "^1.2.3",
    "vue-loader": "^7.3.0",
    "vue-resource": "^1.2.1",
    "webpack": "^2.2.1",
    "webpack-dev-middleware": "^1.8.4",
    "webpack-dev-server": "^1.16.2",
    "webpack-hot-middleware": "^2.13.1"
  },
  "dependencies": {
    "vue": "^2.0.0",
    "vue-router": "^2.0.0"
  },
  "scripts": {
    "build": "webpack --display-modules --display-chunks --config webpack.prod.config.js",
    "dev": "cross-env webpack --hide-modules --display-chunks --config webpack.dev.config.js",
    "test": "cross-env webpack  --config webpack.config.js"
  }
}
复制代码

注明:scripts 设置了一些执行的命令 如dev 就是执行dev环境下webpack编译用的命令 控制台之行:npm run dev即可

2.webpack  配置文件 (有些配置的路径 按项目改变)

(1)webpack.config.js

复制代码
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
    /* 输入文件 */
    entry:  {
        // path.resolve([from ...], to) 将to参数解析为绝对路径
        index:path.resolve(__dirname, './resources/js/src/index.js'),
        // 需要被提取为公共模块的群组
        vendors:['vue','vue-router','three','convex'],
    },
    output: {
        /* 输出目录,没有则新建 */
        path: path.resolve(__dirname, './public/js/'),
        /* 静态目录,可以直接从这里取文件 */
        //publicPath: './resources/js/dist/',
        /* 文件名 */
        filename: '[name].[hash].js',
    },
    resolve:{
      extensions: ['.js', '.css', '.scss','.vue'],
      alias: {
        'vue$': path.resolve(__dirname,'./node_modules/vue/dist/vue.js'),
        'vue-router$':path.resolve(__dirname,'./node_modules/vue-router/dist/vue-router.js'),
        'three$':path.resolve(__dirname,'./resources/js/lib/threejs/build/three.min.js'),
        'convex$':path.resolve(__dirname,'./resources/js/lib/convex.js'),
      }
    },
    module: {
        rules: [
            /* 用来解析vue后缀的文件 */
            {
                test: /\.vue$/,
                use: ['vue-loader']
            },
            /* 用babel来解析js文件并把es6的语法转换成浏览器认识的语法 */
            {
                test: /\.js$/,
                loader: 'babel-loader',
                /* 排除模块安装目录的文件 */
                exclude: /node_modules/,
                options:{
                    presets: ['es2015', 'stage-0'],  
                    plugins: ['transform-runtime']                      
                }
            },
            {  
                test: /\.css$/,                  
                // 将样式抽取出来为独立的文件
                loader: ExtractTextPlugin.extract({fallback:"style-loader", use:["css-loader","postcss-loader"]}),
                exclude: /node_modules/
            },
            // 使用less-loader、autoprefixer-loader、css-loader和style-loade 加载 .less 结尾的文件
            {  
                test: /\.scss$/,                  
                // 将样式抽取出来为独立的文件
                use:['style-loader','css-loader','autoprefixerx','sass-loader'], 
                exclude: /node_modules/
            },           
            // 加载图片
            {
                test: /\.(png|jpg|gif)$/,
                loader: 'url-loader',
                options: {
                    // 把较小的图片转换成base64的字符串内嵌在生成的js文件里
                    limit: 10000,
                    // 路径和生产环境下的不同,要与修改后的publickPath相结合
                    name: 'img/[name].[ext]?[hash:7]'
                }
            },
            // 加载图标
            {
                test: /\.(eot|woff|woff2|svg|ttf)([\?]?.*)$/,
                loader: 'file-loader',
                options: {                   
                    limit: 10000,
                    // 路径和生产环境下的不同,要与修改后的publickPath相结合
                    name:'fonts/[name].[ext]?[hash:7]',
                    prefix:'font'
                }
            }
        ]
    },
    //devtool: '#eval-source-map',
}
复制代码

注明:webpack2.0中loader名称要补全 如sass-loader 之前可以省略-loader这样的后缀 但是现在必须写全 否则无法编译

2.webpack.dev.conifg.js

复制代码
// 引入依赖模块
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');

// 引入基本配置
var config = require('./webpack.config.js');

// 必须修改原配置中网站运行时的访问路径,相当于绝对路径,修改完之后,当前配置文件下的很多相对路径都是相对于这个来设定;
// 注意:webpack-dev-server会实时的编译,但是最后的编译的文件并没有输出到目标文件夹,而是保存到了内存当中
config.output.publicPath = '/game/laravel-master/public/js/';

// 重新配置插件项
config.plugins = [
    // 位于开发环境下
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: '"development"'
        }
    }),
    // 自动生成html插件,如果创建多个HtmlWebpackPlugin的实例,就会生成多个页面
    new HtmlWebpackPlugin({
        // 生成html文件的名字,路径和生产环境下的不同,要与修改后的publickPath相结合,否则开启服务器后页面空白
        filename: '../../resources/views/dist/index.blade.php',
        // 源文件,路径相对于本文件所在的位置
        template: path.resolve(__dirname, './resources/views/index.blade.php'),
        // 需要引入entry里面的哪几个入口,如果entry里有公共模块,记住一定要引入
        chunks: ['vendors','index'],
        // 要把<script>标签插入到页面哪个标签里(body|true|head|false)
        inject: 'body',
        // 生成html文件的标题
        title:''
        // hash如果为true,将添加hash到所有包含的脚本和css文件,对于解除cache很有用
        // minify用于压缩html文件,其中的removeComments:true用于移除html中的注释,collapseWhitespace:true用于删除空白符与换行符
    }),    

    // 提取css单文件的名字,路径和生产环境下的不同,要与修改后的publickPath相结合
    new ExtractTextPlugin("[name].[contenthash].css"),    

    // 提取入口文件里面的公共模块
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendors',
        filename: 'vendors.js',
    }),  

   
    new CleanWebpackPlugin(['js','views','css'],{
        root:path.resolve(__dirname, './public/'),
        verbose: true,
        dry: false,
        //exclude: ['shared.js']
    }),  
    new CleanWebpackPlugin(['views/dist'],{
        root:path.resolve(__dirname, './resources/'),
        verbose: true,
        dry: false,
        //exclude: ['shared.js']
    }), 
    // 为组件分配ID,通过这个插件webpack可以分析和优先考虑使用最多的模块,并为它们分配最小的ID
    //new webpack.optimize.OccurenceOrderPlugin(),

    // 模块热替换插件
    //new webpack.HotModuleReplacementPlugin(),

    // 允许错误不打断程序
    //new webpack.NoErrorsPlugin(),

    // 全局挂载插件
    new webpack.ProvidePlugin({
        Vue: "vue",
        THREE:'three'
    })        
];

module.exports = config;
复制代码

注明:HtmlWebpackPlugin inject 最好还是配置为body 会规避一些问题 (如 渲染速度 加载时序等)

二 vue项目

1。项目结构  (用的laravel php框架 webpack中的部分路径与该项目结构一致)

2.看下主视图文件 index.blade.php (这个文件由于用的laravel框架 目前没找到怎么改后缀名)

复制代码
<!DOCTYPE html>
<html>
    <head>
        <title>Laravel</title>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <div id="app">

        </div>
        
    <script type="text/javascript" src="/game/laravel-master/public/js/vendors.js"></script><script type="text/javascript" src="/game/laravel-master/public/js/index.f6c1bc018a4da91a571e.js"></script></body>
</html>
复制代码

注明:视图文件 什么都没做 就放一个用于vue实例挂载的元素 js文件也是用webpack编译后插入的

3. resources - js - src -index.js 项目的入口文件(es6语法)

复制代码
import App from './pages/app.vue';
import VueRouter from 'vue-router';
import VueResource from 'vue-resource';

Vue.use(VueRouter);
Vue.use(VueResource);


const main = resolve => {
    require.ensure(['./pages/main.vue'],()=>{
        resolve(require('./pages/main.vue'))
    })
}


const router = new VueRouter({
  routes: [{
          path:'/page',
          component: main,
      }
  ]
})


Vue.http.options.emulateJSON = true;

Vue.http.interceptors.push((request, next)  =>{


    next((response) => {
        return response
    });
   
});

const app = new Vue({
  router:router,
  render: h => h(App),
}).$mount('#app')
复制代码

 注明:创建了Vue实例并挂载在id为app的元素上,并创建了一个简单的路由实例 

4.app.vue 文件 什么也没做 就是使用<router-view></router-view>标签,它用于渲染匹配的组件 和 加载一个common.scss文件设置一些页面全局样式

复制代码

<template>
<router-view></router-view>
</template>

<script>
export default {
components: {

}
}
</script>

<style scoped lang='sass-loader'>
@import '../../../css/src/common.scss';
</style>

复制代码

5.main.vue  基本上写了单页面组件所有能用到常用属性 

复制代码
<template>
    <div class="data-webgl-main" ref="canvasbox">
        <canvas ref="canvas"></canvas>
    </div>
</template>

<script >


    export default{
   //监听父传递的变量和函数 props:[ ],
     //声明用到组件 components:{ },
    //组建的数据 data () { return { vinit:'', vscene:'', vcamera:'', vrenderer:'', vlight:'', vgeometry:'', vmaterial:'', vcube: '', vsphere:'', vline:'', vspGroup:'', vhullMesh:'', vcloud:'' } },
    //组建加载完执行 mounted (){ this.vscene = new THREE.Scene(); this.vcamera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000); this.vrenderer = new THREE.WebGLRenderer({canvas:this.$refs.canvas,antialias : true}); this.finitRender(); this.finitCamera(); this.finitScene(); this.finitLight(); this.finitMesh(); //this.fgeneratePoints(); this.fcreatePointCloud(3,true,0.6,true, 0xffffff); this.frender(); },
    //组建被创建触发 created () { },
//监听路由和一些变量的变化出发 监听函数要注意 this的指向 watch:{ },
//组建用到的所有方法 methods:{ frender (){ // this.vrenderer.clear(); // this.vcamera.position.x = this.vcamera.position.x + 1; // this.vcube.rotation.x += 0.02; // this.vcube.rotation.y += 0.02; // this.vcube.rotation.z += 0.02; // this.vline.rotation.z += 0.01; // this.vspGroup.rotation.y = this.vhullMesh.rotation.y; // this.vhullMesh.rotation.y += 0.01; var vertices = this.vcloud.geometry.vertices; vertices.forEach(function (v) { v.y = v.y - (v.velocityY); v.x = v.x - (v.velocityX); if (v.y <= 0) v.y = 60; if (v.x <= -20 || v.x >= 20) v.velocityX = v.velocityX * -1; }); this.vrenderer.render(this.vscene, this.vcamera); requestAnimationFrame(this.frender); }, finitRender (){ this.vrenderer.setClearColor(0x000000,1.0); this.vrenderer.shadowMapEnabled = true; this.vrenderer.setSize(window.innerWidth,window.innerHeight); }, finitCamera (){ this.vcamera.position.x = 20; this.vcamera.position.y = 40; this.vcamera.position.z = 110; // this.vcamera.up.x = 0; // this.vcamera.up.y = 0; // this.vcamera.up.z = 0; this.vcamera.lookAt(new THREE.Vector3(20, 30, 0)) }, finitScene (){ }, finitLight (){ // let light = new THREE.AmbientLight(0xFFFFFF); // light.position.set(100, 100, 200); // this.vscene.add(light); // light = new THREE.PointLight(0x00FF00); // light.position.set(0, 0,300); // this.vscene.add(light); // let light = new THREE.SpotLight(0xFFFFFF); // light.position.set(-40,60,-10); // light.castShadow = true; // this.vscene.add(light); var ambientLight = new THREE.AmbientLight(0x0c0c0c); this.vscene.add(ambientLight); // add spotlight for the shadows var spotLight = new THREE.SpotLight(0xffffff); spotLight.position.set(-40, 60, -10); spotLight.castShadow = true; this.vscene.add(spotLight); }, finitMesh (){ // var geometry = new THREE.CylinderGeometry( 100,150,400); // var material = new THREE.MeshLambertMaterial( { color:0xFFFF00} ); // var mesh = new THREE.Mesh( geometry,material); // mesh.position.add(new THREE.Vector3(0,0,0)); // var planeGeometry = new THREE.PlaneGeometry(60,20,1,1); // var planeMaterial = new THREE.MeshLambertMaterial({color:0xffffff}); // var plane = new THREE.Mesh(planeGeometry,planeMaterial); // plane.rotation.x = -0.5*Math.PI; // plane.position.x = 15; // plane.position.y = 0; // plane.position.z = 0; // plane.receiveShadow = true; // this.vscene.add(plane); // var cubeGeometry = new THREE.CubeGeometry(4,4,4); // var cubeMaterial = new THREE.MeshLambertMaterial({color:0xff0000,wireframe:false}); // var cube = new THREE.Mesh(cubeGeometry,cubeMaterial); // cube.position.x = -4; // cube.position.y = 3; // cube.position.z = 0; // cube.castShadow = true; // this.vcube = cube; // this.vscene.add(cube); // var sphereGeometry = new THREE.SphereGeometry(4,20,20); // var sphereMaterial = new THREE.MeshLambertMaterial({color:0x7777ff,wireframe:false}); // var sphere = new THREE.Mesh(sphereGeometry,sphereMaterial); // sphere.position.x = 20; // sphere.position.y = 4; // sphere.position.z = 2; // this.vsphere = sphere; // this.vscene.add(sphere); // this.vcube = new THREE.Mesh(); // var mats = []; // mats.push(new THREE.MeshBasicMaterial({color:0x009e60})) // mats.push(new THREE.MeshBasicMaterial({color:0x0051ba})) // mats.push(new THREE.MeshBasicMaterial({color:0xffd500})) // mats.push(new THREE.MeshBasicMaterial({color:0xff5800})) // mats.push(new THREE.MeshBasicMaterial({color:0xc41e3a})) // mats.push(new THREE.MeshBasicMaterial({color:0xffffff})) // var faceMaterial = new THREE.MeshFaceMaterial(mats); // for(var x=0;x<3;x++){ // for(var y = 0;y<3;y++){ // for(var z=0;z<3;z++){ // var cubeGeom = new THREE.CubeGeometry(2.9,2.9,2.9); // var cube = new THREE.Mesh(cubeGeom,faceMaterial); // cube.position.add(new THREE.Vector3(x*3-3,y*3,z*3-3)); // this.vcube.add(cube); // } // } // } // this.vscene.add(this.vcube) // var points = this.fgosper(4, 60); // var lines = new THREE.Geometry(); // var colors = []; // var i = 0; // points.forEach(function (e) { // lines.vertices.push(new THREE.Vector3(e.x, e.z, e.y)); // colors[i] = new THREE.Color(0xffffff); // colors[i].setHSL(e.x / 100 + 0.5, ( e.y * 20 ) / 300, 0.8); // i++; // }); // lines.colors = colors; // var material = new THREE.LineBasicMaterial({ // opacity: 1.0, // linewidth: 1, // vertexColors: THREE.VertexColors // }); // this.vline = new THREE.Line(lines, material); // this.vline.position.set(25, -30, -60); // this.vscene.add(this.vline); }, fgosper (a, b) { var turtle = [0, 0, 0]; var points = []; var count = 0; rg(a, b, turtle); return points; function rt(x) { turtle[2] += x; } function lt(x) { turtle[2] -= x; } function fd(dist) { // ctx.beginPath(); points.push({x: turtle[0], y: turtle[1], z: Math.sin(count) * 5}); // ctx.moveTo(turtle[0], turtle[1]); var dir = turtle[2] * (Math.PI / 180); turtle[0] += Math.cos(dir) * dist; turtle[1] += Math.sin(dir) * dist; points.push({x: turtle[0], y: turtle[1], z: Math.sin(count) * 5}); // ctx.lineTo(turtle[0], turtle[1]); // ctx.stroke(); } function rg(st, ln, turtle) { st--; ln = ln / 2.6457; if (st > 0) { // ctx.strokeStyle = '#111'; rg(st, ln, turtle); rt(60); gl(st, ln, turtle); rt(120); gl(st, ln, turtle); lt(60); rg(st, ln, turtle); lt(120); rg(st, ln, turtle); rg(st, ln, turtle); lt(60); gl(st, ln, turtle); rt(60); } if (st == 0) { fd(ln); rt(60); fd(ln); rt(120); fd(ln); lt(60); fd(ln); lt(120); fd(ln); fd(ln); lt(60); fd(ln); rt(60) } } function gl(st, ln, turtle) { st--; ln = ln / 2.6457; if (st > 0) { // ctx.strokeStyle = '#555'; lt(60); rg(st, ln, turtle); rt(60); gl(st, ln, turtle); gl(st, ln, turtle); rt(120); gl(st, ln, turtle); rt(60); rg(st, ln, turtle); lt(120); rg(st, ln, turtle); lt(60); gl(st, ln, turtle); } if (st == 0) { lt(60); fd(ln); rt(60); fd(ln); fd(ln); rt(120); fd(ln); rt(60); fd(ln); lt(120); fd(ln); lt(60); fd(ln); } } }, fgeneratePoints() { // add 10 random spheres var points = []; for (var i = 0; i < 20; i++) { var randomX = -15 + Math.round(Math.random() * 30); var randomY = -15 + Math.round(Math.random() * 30); var randomZ = -15 + Math.round(Math.random() * 30); points.push(new THREE.Vector3(randomX, randomY, randomZ)); } this.vspGroup = new THREE.Object3D(); var material = new THREE.MeshBasicMaterial({color: 0xff0000, transparent: false}); points.forEach((point) => { var spGeom = new THREE.SphereGeometry(0.2); var spMesh = new THREE.Mesh(spGeom, material); spMesh.position.copy(point); this.vspGroup.add(spMesh); }); // add the points as a group to the scene this.vscene.add(this.vspGroup); // use the same points to create a convexgeometry var hullGeometry = new THREE.ConvexGeometry(points); this.vhullMesh = this.fcreateMesh(hullGeometry); this.vscene.add(this.vhullMesh); }, fcreateMesh (geom) { // assign two materials var meshMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00, transparent: true, opacity: 0.2}); meshMaterial.side = THREE.DoubleSide; var wireFrameMat = new THREE.MeshBasicMaterial(); wireFrameMat.wireframe = true; // create a multimaterial var mesh = THREE.SceneUtils.createMultiMaterialObject(geom, [meshMaterial, wireFrameMat]); return mesh; }, fcreatePointCloud(size, transparent, opacity, sizeAttenuation, color) { var texture = THREE.ImageUtils.loadTexture("laravel-master/resources/images/textures/particles/raindrop-3.png"); var geom = new THREE.Geometry(); var material = new THREE.ParticleBasicMaterial({ size: size, transparent: transparent, opacity: opacity, map: texture, blending: THREE.AdditiveBlending, sizeAttenuation: sizeAttenuation, color: color }); var range = 40; for (var i = 0; i < 20; i++) { var particle = new THREE.Vector3( Math.random() * range - range / 2, Math.random() * range * 1.5, Math.random() * range - range / 2); particle.velocityY = 0.1 + Math.random() / 5; particle.velocityX = (Math.random() - 0.5) / 3; geom.vertices.push(particle); } this.vcloud = new THREE.ParticleSystem(geom, material); this.vcloud.sortParticles = true; this.vscene.add(this.vcloud); } },
     //属性的一个实时计算 computed:{ }, } </script> <style lang="sass-loader" scoped> @import '../../../css/src/main.scss'; </style>
复制代码

未完待续。。。。。。

posted @ 2017-03-18 22:16  W+7  阅读(233)  评论(0编辑  收藏  举报