webpack

Webpack 是javascript应用的模块打包器(module bundler)。可以通过配置文件分析项目的结构,找到所有依赖,资源后进行打包输出供浏览器使用。

Webpack主要有四大核心概念:

Entry

webpack打包资源的入口文件,webpack.config.js 配置文件中配置entry属性

module.exports = {
  entry: './path/to/my/entry/file.js'
};

Output

打包后的资源的存放位置,配置output属性

var path = require('path');

module.exports = {
      entry: './path/to/my/entry/file.js',
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'my-first-webpack.bundle.js'
      }
};

Loaders

通过调用外部脚本或工具,对各种格式的文件进行处理打包

test:需要被处理的文件
use:loader的名称,调用处理

var path = require('path');

const config = {
      entry: './path/to/my/entry/file.js',
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'my-first-webpack.bundle.js'
     },
      module: {
           rules: [
              {test: /\.(js|jsx)$/, use: 'babel-loader'}
        ]
      }
};

module.exports = config;

Plugins

插件是用来拓展Webpack功能的,它们会在整个构建过程中生效,执行相关的任务。

const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
const path = require('path');

const config = {
      entry: './path/to/my/entry/file.js',
     output: {
            path: path.resolve(__dirname, 'dist'),
         filename: 'my-first-webpack.bundle.js'
      },
      module: {
        rules: [
              {test: /\.(js|jsx)$/, use: 'babel-loader'}
        ]
      },
     plugins: [
        new webpack.optimize.UglifyJsPlugin(),
        new HtmlWebpackPlugin({template: './src/index.html'})
      ]
};

module.exports = config;

###使用webpack构建本地服务器
Webpack提供一个可选的本地开发服务器,这个本地服务器基于node.js构建,可以实现更改代码后浏览器自动刷新,
首先得安装组件:

npm install --save-dev webpack-dev-server

然后配置

var path = require('path');

const config = {
      entry: './path/to/my/entry/file.js',
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'my-first-webpack.bundle.js'
     },
      module: {
           rules: [
              {test: /\.(js|jsx)$/, use: 'babel-loader'}
        ]
      }

    devServer: {
            contentBase: "./public",//本地服务器所加载的页面所在的目录
            colors: true,//终端中输出结果为彩色
         historyApiFallback: true,//不跳转
         inline: true//实时刷新
      } 
};

module.exports = config;