webpack打包工具之ts版開發框架搭建


本文用兩個框架,一個是threejs,一個是phaser3,其實流程都是一樣。

nodejs、npm是基礎,不再多說!

首先新建一個文件夾命名three-study,然后npm init -y

用webpack工具,第一步要安裝webpack主功能包:

npm i webpack --save-dev

npm i webpack-cli --save-dev

 

 

這兩個包是webpack最基礎的包,如果僅僅只是用於打包,這兩個足夠了(--save-dev的意思是僅僅用於開發環境)。

接下來第二步為里調試方便,需要安裝webpack-dev-server

npm i webpack-dev-server --save-dev

這個包是一個用來快速搭建本地運行環境的工具,通常情況下package.json里的dev或start調試模式都是用它,常用方式:

webpack-dev-server --config webpack.conf.js

其相關配置可自行百度,一般會配置到webpack.conf.js里。

第三步:安裝html-webpack-plugin

npm i html-webpack-plugin --save-dev

這個包就是將打包后的js自動添加到目標index.html模板文件里,省去每次打包都手動操作的麻煩。

第三步:安裝ts-loader,typescript,這是ts語言的配置,所有用到ts開發的都必須安裝這兩個依賴

npm i ts-loader --save-dev
npm i typescript --save-dev

第四步:創建ts配置文件,tsconfig.json,ts的運行必須要有tsconfig文件,否則無法運行和轉換成js,我的配置如下:

{
    "compilerOptions": {
        "module": "commonjs",
        "sourceMap": true,
        "target": "es5"
    },
    "include": [
        "src/*"
    ],
    "exclude": [
        "node_modules"
    ]
}

接下來安裝file-loader和clean-webpack-plugin,file-loader用於資源加載配置,而clean-webpack-plugin則僅僅是打包的時候清除本地原來的打包文件,相當於保持最新,非必須

npm i file-loader --save-dev
npm i clean-webpack-plugin --save-dev

到這里所有工具依賴全部安裝完成,接下來就是我們要開發的包如phaser或threejs,這里注意一定要安裝到依賴環境,即--save 而不是--save-dev

npm i three --save

整個package.json依賴如下

{
  "name": "three-study",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start":"webpack-dev-server --config webpack.conf.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "file-loader": "^5.0.2",
    "html-webpack-plugin": "^3.2.0",
    "ts-loader": "^6.2.1",
    "typescript": "^3.7.3",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.9.0"
  },
  "dependencies": {
    "three": "^0.111.0"
  }
}

 

好了,接下來配置webpack.conf.js文件,讓程序運行起來,我的配置如下

const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode:'development',
    entry:'./src/Main.ts',
    output:{
        path:path.resolve(__dirname,'./public'),
        filename:'app.bundle.js'
    },
    devServer:{
        //設置服務器訪問的基本目錄
        contentBase:path.resolve(__dirname,'./public'),
        host:'172.18.27.110',
        port:1222, // 設置端口號
        inline:true 
    },
    module:{
        rules:[
            {
                test:/\.tsx?$/,
                use:'ts-loader',
                exclude:/node_modules/
            },
            {
                test:/\.(png|jpe?g|gif|svg)(\?.*)?$/,
                use:{
                    loader:'file-loader',
                    options:{
                        name:'[name].[ext]',
                        outputPath:'assets/'
                    }
                }
            }
        ]
    },
    resolve:{
        extensions:['.ts','.tsx','.js']
    },
    devtool:"eval",
    plugins:[
        new HtmlWebpackPlugin({
            template:'index.html'
        })
    ]
}

其中172.18.27.110是我自己電腦的局域網ip,其他各項配置均可查詢官方文檔,這里不再扯遠。

最后一步,根目錄創建一個index.html模板文件,然后創建一個src和public文件夾,public文件夾主要用來存放資源,在src下創建一個Main.ts文件,編寫代碼如下

import * as THREE from 'three'

class Main{
    constructor(){
        this.init();
    }
    private scene:THREE.Scene;
    private camera:THREE.Camera;
    private renderer:THREE.WebGLRenderer;
    private myCube:THREE.Mesh;
    private init(){
        let scene = new THREE.Scene();
        this.scene = scene;
        let camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,.01,1000);
        this.camera = camera;
        let renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth,window.innerHeight);
        document.body.appendChild(renderer.domElement);
        this.renderer = renderer;

        let geometry = new THREE.BoxGeometry(1,1,1);
        let material = new THREE.MeshBasicMaterial({color:0xfff000});
        let cube = new THREE.Mesh(geometry,material);
        scene.add(cube);
        this.myCube = cube;

        camera.position.z = 5;

        this.animate();
    }

    private animate(){
        requestAnimationFrame(this.animate.bind(this));
        this.renderer.render(this.scene,this.camera);
        this.loop();
    }

    private loop(){
        this.myCube.rotation.x += 0.01;
        this.myCube.rotation.y += 0.01;
        this.myCube.rotation.z += 0.01;
    }
}
new Main();

在命令行運行npm run start,然后打開瀏覽器輸入172.18.27.110:1222即可看到如下效果

 

 對於phaser,也是如此配置,這里僅僅配置里一個dev環境,其實還有個線上打包環境,我一般分成dev.conf.js和prd.conf.js,分別代表dev和生產環境,這里有個生產環境配置可作參考

const path = require("path");
const CleanWebpackPlugin = require("clean-webpack-plugin").CleanWebpackPlugin;
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode:'production',
    devtool:"source-map",
    entry:'./src/Main.ts',
    output:{
        filename:'js/[name].[chunkhash].js',
        path:path.resolve(__dirname,'.././dist')
    },
    module:{
        rules:[
            {
                test:/\.tsx?$/,
                use:'ts-loader',
                exclude:/node_modules/
            },
            {
                test:/\.(png|jpe?g|gif|svg)(\?.*)?$/,
                use:{
                    loader:'file-loader',
                    options:{
                        name:'[name].[ext]',
                        outputPath:'assets/'
                    }
                }
            }
        ]
    },
    resolve:{
        extensions:['.ts','.tsx','.js']
    },
    optimization:{
        splitChunks:{
            name:"vendor",
            chunks:"all"
        }
    },
    plugins:[
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template:'index.html'
        })
    ]
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM