webpack Javascript + CSS +字体+图片示例

示例

必修模块

npm install --save-dev webpack extract-text-webpack-plugin file-loader css-loader style-loader

资料夹结构

.
└── assets
    ├── css
    ├── images
    └── js

webpack.config.js

const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const glob = require('glob');

module.exports = {
  entry: {
    script: path.resolve(__dirname, './assets/js/app.js'),
    style: path.resolve(__dirname, './assets/css/app.css'),
    images: glob.sync(path.resolve(__dirname, './assets/images/**/*.*')),
  },
  context: __dirname,
  output: {
    path: path.resolve('./dist/assets'),
    publicPath: '/dist/assets',
    filename: '[name].js',
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: 'css-loader'
        }),
      },
      {
        test: /(\.woff2?|\.woff|\.ttf|\.eot|\.svg)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?name=[name]-[hash:6].[ext]',
      },
      {
        test: /\.(png|jpe?g|gif|ico)$/,
        loader: 'file-loader?name=[name].[ext]',
      },
    ],
  },
  plugins: [
    new ExtractTextPlugin('app.css' /* optional: , { allChunks: true } */),
  ],
};

glob.sync('./assets/images/**/*.*') 将需要images文件夹中的所有文件作为条目。

ExtractTextPlugin将获取生成的输出并创建捆绑css文件。