webpack打包詳細配置
阿新 • • 發佈:2018-11-09
webapck.base.config.js
/** * Created by msw on 2018/4/19. */ const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const fs = require('fs'); const babelrc = JSON.parse(fs.readFileSync('./.babelrc')); require('babel-register')(babelrc); const config = require('./config/config'); //判斷當前執行環境是開發模式還是生產模式 const nodeEnv = process.env.NODE_ENV || 'development'; //獲取package.json檔案中script設定的NODE_ENV環境 var isPro = nodeEnv === 'production '; console.log('當前執行環境:', isPro ? 'production' : 'development'); var rootPath = "./src"; var resolve = function (dir) { return path.join(__dirname, dir); }; //設定外掛 var plugins = [ //使用外掛進行抽取樣式 new ExtractTextPlugin('css/[name].css') ]; var array = config.htmlPlugin(rootPath); array.forEach(function(v){ var str = v.replace(rootPath+'/',""); console.log(str); plugins.push( new HtmlWebpackPlugin({ filename: v.replace(rootPath+"/",""), template: v, chunks:[str.replace(".html","")], hash: true, // hash選項的作用是 給生成的 js 檔案一個獨特的 hash 值,該 hash 值是該次 webpack 編譯的 hash 值。預設值為 false showErrors: true, // showErrors 的作用是,如果 webpack 編譯出現錯誤,webpack會將錯誤資訊包裹在一個 pre 標籤內,屬性的預設值為 true inject: true, // 注入選項 有四個值 ture: 預設值,script標籤位於html檔案的 body 底部, body: 同 true, head: script標籤位於html檔案的 head 底部,false:不注入script標籤 minify:{ removeComments:true //是否壓縮時 去除註釋 }, cache: true // 預設值是 true。表示只有在內容變化時才生成一個新的檔案 }) ) }) //根據環境設定使用的外掛 if (isPro) { //內建外掛,這裡面的標識就相當於全域性變數,直接使用配置的標識。 new webpack.DefinePlugin({ 'process.env':{ 'NODE_ENV': JSON.stringify(nodeEnv) } }), //去壓縮你的JavaScript程式碼 plugins.push( new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ) } else { //內建外掛,這裡面的標識就相當於全域性變數,直接使用配置的標識。 new webpack.DefinePlugin({ 'process.env':{ 'NODE_ENV': JSON.stringify(nodeEnv) } }), plugins.push( //模組熱替換 new webpack.HotModuleReplacementPlugin() ) } baseConfigs = { devtool: !isPro && 'cheap-module-eval-source-map', //webpack sourcemap模式map entry: config.entry(rootPath), //entry: { //app: ['./src/main'] //}, output: { filename: '[name].js', path: path.resolve(__dirname, 'static'), ////當生成的資原始檔和站點不在同一地方時需要配置改地址 e.g.:站點在src,資源生成到/src/static/dist,那麼publicPath="/static/dist" //publicPath: isPro ? './' : './', chunkFilename: '[name].[hash].js' }, plugins: plugins, node: { fs: 'empty' }, resolve: { extensions: ['.js', '.vue', '.less', '.css'], //自動解析確定的擴充套件。預設值為: modules: [ //告訴 webpack 解析模組時應該搜尋的目錄。此時的配置是node_modules目錄優先於./src目錄 path.resolve(__dirname, 'node_modules'), path.join(__dirname, './src') ], alias: { 'vue': 'vue/dist/vue.js' //代理引入名稱,在require("components")相當於require("src/components") } }, module: { rules: [{ test: /\.js$/, //正則表示式,用於匹配到的檔案 use: ['babel-loader'], //字串或者陣列,處理匹配到的檔案,陣列模式 exclude: /node_modules/, //exclude 表示哪些目錄中的 .js 檔案不要進行 babel-loader include: resolve('/') //include 表示哪些目錄中的 .js 檔案需要進行 babel-loader },{ test: /\.vue$/, use: ['vue-loader'], exclude: /node_modules/, include: resolve('src') }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, use: ['url-loader?limit=8192&name=images/[hash:16].[ext]'] }, { test: /\.(less|css)$/, use: ExtractTextPlugin.extract({ use: ['css-loader', 'less-loader'], fallback: 'style-loader' }) }] }, devServer: { contentBase: resolve('/'), //告訴伺服器從哪裡提供內容,預設情況下,將使用當前工作目錄作為提供內容的目錄,但是你可以修改為其他目錄 historyApiFallback: true, //當使用HTML5 History API,任意的 404 響應可以提供為 index.html 頁面。通過傳入以下啟用 compress: true, //一切服務都啟用gzip 壓縮 port: 8088, //指定要監聽請求的埠號: //host: "127.0.0.1", //指定使用一個 host hot: true, //啟用 webpack 的模組熱替換特性: inline: true, //在 dev-server 的兩種不同模式之間切換。預設情況下,應用程式啟用內聯模式(inline mode)。這意味著一段處理實時過載的指令碼被插入到你的包(bundle)中,並且構建訊息將會出現在瀏覽器控制檯。 stats: { // 增加資源資訊 assets: true, // 增加子級的資訊 children: false, // 增加內建的模組資訊 modules: false, // 增加包資訊(設定為 `false` 能允許較少的冗長輸出) chunks: false, // 增加 publicPath 的資訊 publicPath: false, // 增加時間資訊 timings: true, // 增加提示 warnings: true, // `webpack --colors` 等同於 colors: { green: '\u001b[32m', } }, } }; exports.baseConfig = baseConfigs;
webpack.config.js
入口檔案
/**
* Created by msw on 2018/4/19.
*/
const baseConfig = require('./webpack.base.config');
module.exports = baseConfig.baseConfig;
package.json
{ "name": "vue2-web", "version": "1.0.0", "description": "vue2、webpack2框架", "main": "index.js", "scripts": { "start": "set NODE_ENV=development && webpack-dev-server", "build": "set NODE_ENV=production && webpack -p --progress" }, "author": "hyy", "license": "ISC", "devDependencies": { "babel-core": "^6.24.1", "babel-helper-vue-jsx-merge-props": "^2.0.2", "babel-loader": "^6.4.1", "babel-plugin-syntax-jsx": "^6.18.0", "babel-plugin-transform-runtime": "^6.23.0", "babel-plugin-transform-vue-jsx": "^3.4.2", "babel-polyfill": "^6.23.0", "babel-preset-es2015": "^6.24.1", "babel-preset-flow-vue": "^1.0.0", "babel-preset-stage-0": "^6.24.1", "babel-preset-stage-2": "^6.24.1", "css-loader": "^0.28.0", "extract-text-webpack-plugin": "^2.1.0", "file-loader": "^0.11.1", "html-webpack-plugin": "^2.28.0", "jquery": "^3.3.1", "less": "^2.7.2", "less-loader": "^4.0.3", "style-loader": "^0.16.1", "url-loader": "^0.5.8", "vue-loader": "^11.3.4", "vue-template-compiler": "^2.2.6", "webpack": "^2.5.1", "webpack-dev-server": "^2.5.2" }, "dependencies": { "swiper": "^3.4.2", "vue": "^2.2.6", "vue-resource": "^1.3.1", "vue-router": "^2.4.0" } }
.babelrc
{
"presets": ["es2015", "flow-vue", "stage-0", "stage-2"],
"plugins": ["transform-vue-jsx"],
"comments": false,
"env": {
"production": {
"plugins": [
["transform-runtime", { "polyfill": false, "regenerator": false }]
]
}
}
}
config.js
在這一個配置檔案中主要是通過遍歷獲取資料夾下的所有檔案及路徑
/**
* Create By MOSHUNWEI At 2018-07-05
* 入口檔案,通過遍歷獲取所有入口js,入後輸出到相應的目錄
*/
const fs = require('fs');
//遍歷獲取所有js節點
var getEntries = function(url,map,rootPath) {
var files = [];
//判斷給定的路徑是否存在
if( fs.existsSync(url) ) {
//返回檔案和子目錄的陣列
files = fs.readdirSync(url);
//console.log(files);
files.forEach(function(file,index){
var curPath = url + "/" + file;
// var curPath = path.join(url,file);
//fs.statSync同步讀取資料夾檔案,如果是資料夾,在重複觸發函式
if(fs.statSync(curPath).isDirectory()) { // recurse
getEntries(curPath,map,rootPath);
// 是檔案delete file
} else {
if(curPath.match(".*\.js$")==null?false:true){
var val = curPath.replace("\.js","").replace(rootPath+"/",'');
map[val]=val;
};
}
});
}else{
console.log("給定的路徑不存在,請給出正確的路徑");
}
};
function entries(path){
var map = {};
getEntries(path,map,path);
return map;
};
var getHtml = function(url,plugins) {
var files = [];
//判斷給定的路徑是否存在
if( fs.existsSync(url) ) {
//返回檔案和子目錄的陣列
files = fs.readdirSync(url);
files.forEach(function(file,index){
var curPath = url + "/" + file;
// var curPath = path.join(url,file);
//fs.statSync同步讀取資料夾檔案,如果是資料夾,在重複觸發函式
if(fs.statSync(curPath).isDirectory()) { // recurse
getHtml(curPath,plugins);
// 是檔案delete file
} else {
if(curPath.match(".*\.html$")==null?false:true){
plugins.push(curPath);
};
}
});
}else{
console.log("給定的路徑不存在,請給出正確的路徑");
}
};
function htmlPlugins(path){
var plugins = [];
getHtml(path,plugins);
return plugins;
};
module.exports = {
entry:entries,
htmlPlugin:htmlPlugins
}
整個webpack專案的結構
就是通過webapck打包後把src目錄下的js,vue,css,html都全部一起打包到static目錄之下。
執行後的截圖