2017-06-17 83 views
-1

我是webpack新手。 我想綁定我的項目,這是寫在打字稿,但目的地文件具有相同的打字稿,這是瀏覽器不可讀的代碼,所以我的配置下面的混亂步驟是什麼? 該項目在html中使用腳本標記正常工作,但我需要將它們作爲捆綁包,然後製作縮小文件。如何將打字稿與webpack捆綁在一起?

的package.json

{ 
    "name": "filemanager", 
    "version": "1.0.0", 
    "description": "controls files using http for web hosting that has no FTP protocol.", 
    "main": "index.js", 
    "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1" 
    }, 
    "devDependencies": { 
    "ts-loader": "^2.1.0", 
    "typescript": "^2.3.4", 
    "webpack": "^1.15.0" 
    } 
} 

tsconfig.json

{ 
    "compilerOptions": { 
    "sourceMap": true 
    }, 
    "files": [ 
     "./ts/app.ts" 
    ] 
} 

wepback.config.js

var path = require('path'); 
var webpack = require('webpack'); 
module.exports={ 
    devtool: "source-map", 
    entry: './ts/app.ts', 
    output:{ 
     path: './build', 
     filename: 'app.bundle.js' 
    }, 
    rules:[{ 
     test: /\.tsx?$/, 
     include: path.resolve(__dirname, "ts/"), 
     loader: "ts-loader", 
     exclude: /node_modules/, 
    }], 
    resolve:{ 
     extensions: ["", ".webpack.js", ".web.js", ".ts", ".js"] 
    }, 
    // watch: true 
} 

我的應用程序路徑I小號./ts/app.ts

import { controler } from './control'; // error stop here "Uncaught SyntaxError: Unexpected token import" 
import { Injector } from './Injector'; 

window.onload =()=>{ 
    var DI = new Injector; 
    DI.process(controler); 
} 

Injector.ts

export class Injector{ 

    private dependencies = {}; 
    process(target){ 
     let mainFun = null, 
      // tmpFun =()=>{}, 
      // FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m, 
      // FN_ARG_SPLIT = /,/, 
      // FN_ARG = /^\s*(_?)(\S+?)\1\s*$/, 
      // STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, 
      // text = target[2].toString(), 
      // args = text.match(FN_ARGS)[1].replace(/\s/g, '').split(','); 
      args = []; 

     for(let key in target){ 
      if(typeof target[key] != 'function'){ 
       args.push(target[key]); 
      }else{ 
       mainFun = target[key]; 
       break; 
      } 
     } 
     // console.log(args, mainFun); 

     // tmpFun.prototype = mainFun.prototype; 
     // var instance = new tmpFun(); 
     // console.log(tmpFun.prototype); 

     mainFun.prototype.constructor.apply(mainFun.prototype, this.getDependencies(args)); 
     // return instance; 
    } 
    getDependencies(arr){   
     return arr.map((value)=>{ 
      return this.dependencies[value]; 
     });    
    } 
    register(name, dependency){ 
     this.dependencies[name] = new dependency; 
    } 

}; 

control.ts

declare var $: any; 
declare var Promise: any; 
export let controler = ['IMModel','IMView',class IMControl{ 
    private im_model  : any; 
    private im_view   : any; 
    private wh    : number;  // save document height; 
    private ww    : number;  // save document width; 
    private siteMap   = $('.aside'); 
    private nextContainer : any;   // store the next container for the new directories 
    public loadedPaths  = [];   // used to store all directories in aside menu to save repated requests 
    public loadedFiles  = [];   // used to store all files to save repated requests 
    private currentPath  = null   // used to store current path for upload new files in a specific directory 
    private currentItem  = null   // used to store current item to be ready with any selection choices 
    private searchResult = []; 
    private pathNavigator = $('.navbar .path'); 
    private filesList  = $('.explorer .filesList'); 
    private isUploading  : boolean = false; 
    private isAJAXFinished : boolean = true; // This is used to hold any action till response come back. 
    private newRequestReady : boolean = true; // This is used to check if the are more files to be loaded from the server otherwise it will be false. 
    private items   = []; 
    private itemsIterations = 0; 
    private page   = 1; 
    private defaultPath : any = [{ 
             type: 'folder', 
             name: 'Root', 
             path: './img', 
             ext: 'folder', 
             chuldren: null 
            }]; 
    private filesTypeMap = { 'avi'  :'<i class="fa fa-file-video-o" aria-hidden="true"></i>', 
           'php'  :'<i class="fa fa-file-code-o" aria-hidden="true"></i>', 
           'mkv'  : '<i class="fa fa-video-camera" aria-hidden="true"></i>', 
           'mp4'  : '<i class="fa fa-video-camera" aria-hidden="true"></i>', 
           'folder' : '<i class="fa fa-folder" aria-hidden="true"></i>', 
           'default' : '<i class="fa fa-file" aria-hidden="true"></i>' }; 
    constructor(IMModel, IMView){ 
     this.im_model  = IMModel; 
     this.im_view  = IMView; 
     this.onInit(); 
    } 
    // rest of the code 
}]; 

回答

-2

我解決我的問題,主要的研究之後。對於任何額外的信息,你可以看到我的webpack模板。

這解決了我的問題在這裏

的package.json

{ 
    "name": "ProjectName", 
    "version": "1.0.0", 
    "description": "Description", 
    "main": "index.js", 
    "scripts": { 
    "clean": "rimraf ./dist/*", 
    "prod": "cross-env NODE_ENV=production webpack -p --progress", 
    "dev": "cross-env NODE_ENV=production webpack -d --progress --watch", 
    "serve": "webpack-dev-server", 
    "mini": "npm-run-all clean prod", 
    "build": "npm-run-all clean dev" 
    }, 
    "repository": { 
    "type": "git", 
    "url": "" 
    }, 
    "author": "Me", 
    "license": "ISC", 
    "bugs": { 
    "url": "" 
    }, 
    "homepage": "", 
    "devDependencies": { 
    "cross-env": "^5.0.1", 
    "css-loader": "^0.28.4", 
    "extract-text-webpack-plugin": "^2.1.2", 
    "file-loader": "^0.11.2", 
    "html-webpack-plugin": "^2.28.0", 
    "image-webpack-loader": "^3.3.1", 
    "node-sass": "^4.5.3", 
    "npm-run-all": "^4.0.2", 
    "rimraf": "^2.6.1", 
    "sass-loader": "^6.0.6", 
    "style-loader": "^0.18.2", 
    "svg-inline-loader": "^0.8.0", 
    "ts-loader": "^2.1.0", 
    "typescript": "^2.3.4", 
    "webpack": "^2.6.1", 
    "webpack-dev-server": "^2.4.5" 
    } 
} 

webpack.js

const path = require('path'); 
const webpack = require('webpack'); 
const htmlWebpackPlugin = require('html-webpack-plugin'); 
const ExtractTextPlugin = require("extract-text-webpack-plugin"); 
const publicPath = 'assets/'; 

const extractSass = new ExtractTextPlugin({ 
    filename: "[name].[contenthash].css", 
    disable: isProd, 
    allChunks: true 

}); 
const extractHtml = new htmlWebpackPlugin({ 
    title: 'Admin Panal', 
    minify:{ 
     collapseWhitespace: false 
    }, 
    hash: true, 
    template: './src/index.html' // Load a custom template (ejs by default see the FAQ for details) 
}); 

var isProd = process.env.NODE_ENV === 'production', // this will return true or false depend on package.json 
    cssDev = ["style-loader","css-loader","sass-loader"], 
    cssProd = extractSass.extract({ 
     use:[{ 
       loader: "css-loader", // translates SASS into Common CSS 
       options: {sourceMap: true, convertToAbsoluteUrls: true } // convertTo.. will resolve images path 
      }, { 
       loader: "sass-loader" 
      }], 
     fallback: "style-loader" 
    }); 
var cssConfig = isProd ? cssProd: cssDev; 
module.exports={ 
    devServer: { 
     contentBase: path.join(__dirname, "dist"), 
     compress: true, 
     stats: "errors-only", 
     watchContentBase: true, 
     hot: true, 
     inline: true, 
     open: true, 
     port: 9000, 
     openPage: '' 
    }, 
    devtool: "source-map", // show .map files for better debugging. 
    entry: './src/ts/app.ts', 
    output:{ 
     path: path.resolve(__dirname, 'dist'), 
     filename: 'app.bundle.js' 
    }, 
    resolve: { 
     extensions: ['.js', '.jsx', '.ts', '.tsx', '.scss', '.css'] 
    }, 
    module:{ 
     rules: 
     [{ 
      test: /\.scss$/, 
      use: cssConfig 
     },{ 
      test: /\.tsx?$/, 
      loader: 'ts-loader', 
      exclude: /node_modules/, 
     }, 
     { 
      test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2|json|xml|ico)(\?.*)?$/i, 
      loader: [ 
       'file-loader?name='+publicPath+'[name].[ext]', 
       { 
        loader: 'image-webpack-loader', 
        options: 
        { 
         query: 
         { 
          progressive: true, 
          optimizationLevel: 7, 
          interlaced: false, 
          pngquant: 
          { 
           quality: '65-90', 
           speed: 4 
          } 
         } 
        } 
       } 
      ] 
     }] 
    }, 
    plugins: [ extractHtml, extractSass, 
    new webpack.HotModuleReplacementPlugin(), 
    new webpack.NamedModulesPlugin()] 
} 

這是對模板的引用。

Webpack_Template

+0

對於其他讀者以備將來參考,它是有用的(並且比鏈接更可靠)來總結解決問題的要點。 –

+0

感謝@KoertvanKleef提示。我更新重播。 –

0

我沒有與任何ts-loader經驗所以我不知道它是否有什麼好處,我用awesome-typescript-loader來用webpack傳輸我的打字稿代碼。所以,第一步是通過npm i -D awesome-typescript-loader安裝它,然後修改您的WebPack配置文件中像這樣

var path = require('path'); 
var webpack = require('webpack'); 
module.exports={ 
    devtool: "source-map", 
    entry: './ts/app.ts', 
    output:{ 
     path: './build', 
     filename: 'app.bundle.js' 
    }, 
    rules:[{ 
     test: /\.tsx?$/, 
     include: path.resolve(__dirname, "ts/"), 
     use: "awesome-typescript-loader", // Change here 
     exclude: /node_modules/, 
    }], 
    resolve:{ 
     extensions: ["", ".webpack.js", ".web.js", ".ts", ".js"] 
    }, 
    // watch: true 
} 
+0

謝謝虛擬,但仍然是同樣的問題。 我覺得javascript不理解在ES5中導入,所以它應該被轉換爲等效代碼,但代碼在我的.js文件中仍然是相同的。你可以提供給我的tsconfig.ts配置可能有一些不同的東西! –

+0

將''target':「es5」'添加到您的tsconfig文件 – Dummy