最近一個小項目是用webpack來進行構建的。其中用到了webpack分包異步加載的功能。今天抽時間看了下webpack打包后的文件,大致弄明白了webpack分包及異步加載的套路。
由于這個小項目是用自己寫的一個路由,路由定義好了不同路徑對應下的模板及邏輯代碼:
webpack配置文件:
var path = require('path'), DashboardPlugin = require('webpack-dashboard/plugin'), HtmlWebpackPlugin = require('html-webpack-plugin'), webpack = require('webpack'), ExtractTextPlugin = require('extract-text-webpack-plugin');var PATHS = { app: path.join(__dirname, 'src'), dist: path.join(__dirname, 'dist')}var PKG = require('./package.json');var TARGET = process.env.npm_lifecycle_event; //獲取當前正在運行的腳本名稱var isProduction = function() { return process.env.NODE_ENV === 'production';}module.exports ={ entry: { 'index': path.join(__dirname, 'src/index.js'), 'lib': ['./src/lib/js/index.js'], }, //filename是主入口文件的名稱,即對應的entry //chunkFilename對應的是非主入口文件的名稱,chunk output: { path: PATHS.dist, publicPath: '/static/taxi-driver/', //publicPath 的話是打包的時候生成的文件鏈接,如果是在生產環境當然是用服務器地址,如果是開發環境就是用本地靜態服務器的地址 filename: 'js/register/[name].js', chunkFilename: 'js/register/[name].js', //TODO: build文件中加入hash值 }, //生成source-map文件 devtool: isProduction ? null : 'source-map', devServer: { proxy: { '/api/*': { target: 'http://localhost:3000', secure: false } } }, module: { loaders: [ { test: //.js$/, exclude: /node_modules|picker.min.js/, loader: 'babel' }, { test: //.less$/, loader: ExtractTextPlugin.extract('style', 'css!less') }, { test: //.html$/, loader: 'raw' }, { test: //.css$/, loader: ExtractTextPlugin.extract('style', 'css') }, { test: //.json$/, loader: 'json' } ] }, resolve: { alias: { src: path.join(__dirname, 'src'), modules: path.join(__dirname, 'src/modules'), lessLib: path.join(__dirname, 'src/lib/less'), jsLib: path.join(__dirname, 'src/lib/js'), components: path.join(__dirname, 'src/components') }, extensions: ['', '.js', '.less', '.html', '.json'], }, plugins: [ new HtmlWebpackPlugin({ title: '認證資料', template: './dist/assets/info.html', inject: 'body', filename: 'pages/register/index.html' //輸出html文件的位置 }), new DashboardPlugin(), new ExtractTextPlugin('css/register/style.css'), //將引入的樣式文件單獨抽成style.css文件并插入到head標簽當中,帶有路徑時,最后打包 new webpack.optimize.CommonsChunkPlugin({ name: 'common', filename: 'js/register/common.js', minChunks: 3 }) ]}接下來是定義好的路由文件:
const Router = new Route(); Route .addRoute({ path: 'path1', viewBox: '.public-container', template: require('modules/path1/index.html'), pageInit() { //webpack提供的分包的API. require.ensure require.ensure([], () => { let controller = require('modules/path1/controller'); Router.registerCtrl('path1', new controller('.public-container')); }, 'path1'); } }) .addRoute({ path: 'path2', viewBox: '.public-container', template: require('modules/path2/index.html'), pageInit() { require.ensure([], () => { let controller = require('modules/path2/controller'); Router.registerCtrl('path2', new controller('.public-container')); }, 'path2'); } });
新聞熱點
疑難解答
圖片精選