webpack五大核心概念 - 图1
webpage中文官网

核心概念

入口

  1. module.exports = {
  2. entry: './path/to/my/enter/file.js'
  3. };
  4. /*
  5. 告知webpack从哪个文件开始去阅读去查验代码
  6. */

输出

  1. const path = require('path');
  2. module.exports = {
  3. entry: './path/to/my/enter/file.js',
  4. output: {
  5. path: path.resolve(__dirname, 'dist'),
  6. filename: 'my-first-webpack.bundle.js'
  7. }
  8. };
  9. /*
  10. output是webpack给出的结果
  11. 打包出的路径是什么,名字是什么…
  12. */

Loader

  1. const path = require('path');
  2. module.exports = {
  3. output: {
  4. filename: 'my-first-webpack.bundle.js'
  5. },
  6. module: {
  7. rules: [
  8. { test: /\.txt$/, use: 'raw-loader' }
  9. ]
  10. }
  11. };
  12. /*
  13. raw-loader去处理txt文件
  14. */

插件

  1. const HtmlWebpackPlugin = require('html-webpack-plugin'); //npm安装
  2. const webpack = require('webpack');
  3. module.exports = {
  4. module: {
  5. rules: [
  6. { test: /\.txt$/, use: 'raw-loader' }
  7. ]
  8. },
  9. plugins: [
  10. new HtmlWebpackPlugin({template: './src/index.html'})
  11. ]
  12. }

loader 处理webpack本身不能处理的文件,即非js文件
plugins 能处理更复杂的任务

模式/兼容性

webpack支持所有符合ES5标准的浏览器(不支持IE8及以下的版本)。webpack的import()和require.ensure()需要promise。如果你想要支持旧版本浏览器,在使用这些表达式之前,还需要提前加载polyfill。

  1. npm install --save babel-polyfill

然后,使用 import 将其导入到主bundle文件:
src/index.js

  1. import 'babel-polyfill';
  2. function component() {
  3. var element = document.createElement('div');
  4. element.innerHTML = join(['Hello', 'webpack'], ' ');
  5. return element;
  6. }
  7. document.body.appendChild(component());