Webpack 怎么用

2025-06-21 08:26:05
推荐回答(2个)
回答1:

  1. 为什么用 webpack?
  他像 Browserify, 但是将你的应用打包为多个文件. 如果你的单页面应用有多个页面, 那么用户只从下载对应页面的代码. 当他么访问到另一个页面, 他们不需要重新下载通用的代码.
  他在很多地方能替代 Grunt 跟 Gulp 因为他能够编译打包 CSS, 做 CSS 预处理, 编译 JS 方言, 打包图片, 还有其他一些.
  它支持 AMD 跟 CommonJS, 以及其他一些模块系统, (Angular, ES6). 如果你不知道用什么, 就用 CommonJS.
  2. Webpack 给 Browserify 的同学用
  对应地:
  browserify main.js > bundle.js

  webpack main.js bundle.js

  Webpack 比 Browserify 更强大, 你一般会用 webpack.config.js 来组织各个过程:
  // webpack.config.js
  module.exports = {
  entry: './main.js',
  output: {
  filename: 'bundle.js'
  }
  };

  这仅仅是 JavaScript, 可以随意添加要运行的代码.
  3. 怎样启动 webpack
  切换到有 webpack.config.js 的目录然后运行:
  webpack 来执行一次开发的编译
  webpack -p for building once for production (minification)
  webpack -p 来针对发布环境编译(压缩代码)
  webpack --watch 来进行开发过程持续的增量编译(飞快地!)
  webpack -d 来生成 SourceMaps
  4. JavaScript 方言
  Webpack 对应 Browsserify transform 和 RequireJS 插件的工具称为 loader. 下边是 Webpack 加载 CoffeeScript 和 Facebook JSX-ES6 的配置(你需要 npm install jsx-loader coffee-loader):
  // webpack.config.js
  module.exports = {
  entry: './main.js',
  output: {
  filename: 'bundle.js'
  },
  module: {
  loaders: [
  { test: /\.coffee$/, loader: 'coffee-loader' },
  { test: /\.js$/, loader: 'jsx-loader?harmony' } // loaders 可以接受 querystring 格式的参数
  ]
  }
  };

  要开启后缀名的自动补全, 你需要设置 resolve.extensions 参数指明那些文件 Webpack 是要搜索的:
  // webpack.config.js
  module.exports = {
  entry: './main.js',
  output: {
  filename: 'bundle.js'
  },
  module: {
  loaders: [
  { test: /\.coffee$/, loader: 'coffee-loader' },
  { test: /\.js$/, loader: 'jsx-loader?harmony' }
  ]
  },
  resolve: {
  // 现在可以写 require('file') 代替 require('file.coffee')
  extensions: ['', '.js', '.json', '.coffee']
  }
  };

  5. 样式表和图片
  首先更新你的代码用 require() 加载静态资源(就像在 Node 里使用 require()):
  require('./bootstrap.css');
  require('./myapp.less');

  var img = document.createElement('img');
  img.src = require('./glyph.png');

  当你引用 CSS(或者 LESS 吧), Webpack 会将 CSS 内联到 JavaScript 包当中, require() 会在页面当中插入一个 `