Webpack配置從零到一

Webpack配置從零到一

這不算是初學者的入門文章,也不能算是高端用戶的進階。這只是我本身在配置Webpack過程當中收集整理的一些資料,以及本身經常使用的整個配置流程。由於有時候總是忘了某個東西是怎麼配置的,因此記錄下來用於速查和備忘。css

setup

$ npm init
$ npm install webpack --save-dev # 全局安裝依賴
# or
$ npm install webpack-dev-server --save-dev # 安裝webpack調試工具

basic config

// config/webpack.config.js
const webpack = require('webpack');

// 配置目錄
// 由於咱們的webpack.config.js文件不在項目根目錄下,因此須要一個路徑的配置
const path = require('path');
const CURRENT_PATH = path.resolve(__dirname); // 獲取到當前目錄
const ROOT_PATH = path.join(__dirname, '../'); // 項目根目錄
const MODULES_PATH = path.join(ROOT_PATH, './node_modules'); // node包目錄
const BUILD_PATH = path.join(ROOT_PATH, './public/assets'); // 最後輸出放置公共資源的目錄

module.exports = {
  context: path.join(__dirname, '../'), // 設置webpack配置中指向的默認目錄爲項目根目錄
  entry: {
    index: './public/pages/index.js',
    public: './public/pages/public.js'
  },
  output: {
    path: BUILD_PATH, // 設置輸出目錄
    filename: '[name].bundle.js', // 輸出文件名
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.coffee'] // 配置簡寫,配置事後,書寫該文件路徑的時候能夠省略文件後綴
  },
  module: {
    loaders: [
      // loader 扔在這裏
    ]
  },
  plugins: [
    // 插件扔在這裏
  ]
}

loaders

沒有loader怎麼活! ̄へ ̄node

install css/less/style loader

scss-loader的配置同理less,我的比較經常使用lessreact

$ npm install less --save-dev # install less

$ npm install css-loader style-loader --save-dev # install style-loader, css-loader

$ npm install less less-loader --save-dev # 基於style-loader,css-loader

install url loader

用來處理圖片和字體文件jquery

$ npm install file-loader --save-dev
$ npm install url-loader --save-dev

install babel loader

不能寫ES6的js不叫jswebpack

$ npm install babel-loader babel-core babel-preset-es2015 --save-dev

config loaders

// config/webpack.config.js

module.exports = {
  module: {
    loaders: [
      // style & css & less loader
      { test: /\.css$/, loader: "style-loader!css-loader"},
      { test: /\.less$/, loader: "style-loader!css-loader!less-loader")},
      // babel loader
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: ['babel-loader'],
        query: {
          presets: ['es2015']
          // 若是安裝了React的話
          // presets: ['react', 'es2015']
        }
      },
      // image & font
      { test: /\.(woff|woff2|eot|ttf|otf)$/i, loader: 'url-loader?limit=8192&name=[name].[ext]'},
      { test: /\.(jpe?g|png|gif|svg)$/i, loader: 'url-loader?limit=8192&name=[name].[ext]'},
    ]
  }
}

plugin

ExtractTextPlugin分離CSS

行內插入一坨CSS是萬惡之源 git

-- 我瞎扯的github

# install ExtractTextPlugin
$ npm install extract-text-webpack-plugin --save-dev
// config/webpack.config.js

const ExtractTextPlugin = require("extract-text-webpack-plugin");

module: {
  loaders: [
    // 把以前的style&css&less loader改成
    { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader')},
    { test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css!less') },
  ]
},
plugins: [
  // 分離css
  new ExtractTextPlugin('[name].bundle.css', {
    allChunks: true
  }),
]

設置jQuery全局變量

jQuery很老土?好吧我還真有點贊成你。。但無疑在必定程度上它仍是很方便的。我把jQuery設置成全局變量,這樣的話有時候就能偷懶用下它了。web

$ npm install jquery --save-dev

# 安裝 expose-loader
$ sudo npm install expose-loader --save
// config/webpack.config.js

module: {
  loaders: [
    // expose-loader將須要的變量從依賴包中暴露出來
    { test: require.resolve("jquery"), loader: "expose?$! expose?jQuery" }
  ]
},
plugins: [
  // 把jquery做爲全局變量插入到全部的代碼中
  // 而後就能夠直接在頁面中使用jQuery了
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    'window.jQuery': 'jquery'
  }),
]

CommonsChunkPlugin抽取公共資源

// config/webpack.config.js

entry: {
  jquery: ['jquery']
},
plugins: [
  // public sources
  new webpack.optimize.CommonsChunkPlugin({
    // 與 entry 中的 jquery 對應
    name: 'jquery',
    // 輸出的公共資源名稱
    filename: 'common.bundle.js',
    // 對全部entry實行這個規則
    minChunks: Infinity
  }),
]

UglifyJsPlugin代碼壓縮混淆

// config/webpack.config.js

plugins: [
  new webpack.optimize.UglifyJsPlugin({
    mangle: {
      except: ['$super', '$', 'exports', 'require']
      //以上變量‘$super’, ‘$’, ‘exports’ or ‘require’,不會被混淆
    },
    compress: {
      warnings: false
    }
  })
]

我要用 React!

React + Webpack在我內心是個標配,本身也很喜歡React+Redux+Webpack那一套,因此怎麼少得了它。npm

install

# react
$ npm install react --save
$ npm install react-dom --save

# 喜歡redux?
$ npm install --save redux # redux
$ npm install --save react-redux # 和react配合
$ npm install --save redux-thunk # middleware

# 若是已經裝了babel能夠忽略下面這條
$ npm install babel-loader babel-core babel-preset-es2015 --save-dev

# 可是要用React的話必定記得安裝下面這個
$ npm install babel-preset-react --save-dev

config

loaders: [
  {
    test: /\.jsx?$/,
    exclude: /(node_modules|bower_components)/,
    loader: ['babel-loader'],
    query: {
      presets: ['react', 'es2015']
    }
  }
]

bug ?

在最新的React(V15)裏,若是你按照上面的配置正常使用的話,應該會出現以下的警告:redux

Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See https://fb.me/react-minification for more details.

我記得之前的版本沒有這個警告啊?我在開發環境壓縮它了?那把UglifyJsPlugin拿走試試。。結果仍是同樣。

最後在github React-issue找到了目前的解決方案:

在Webpack的plugins裏添加:

new webpack.DefinePlugin({
  "process.env": { 
     NODE_ENV: JSON.stringify("production") 
   }
})

而後就沒問題了==

end

若是真的要玩的話,webpack能夠有很是多的玩法(看看它插件就知道了)。但webpack終究是一個工具,因此也就沒有特別深刻探究它,知道怎麼用,夠用就行了。

相關文章
相關標籤/搜索