Web 前端开发 让前端飞

webpack学习(1)

2017-07-26  本文已影响0人  FeRookie

概念

webpack是现在JavaScript应用程序打包生成器。当webpack在处理程序的时候,会递归的构建依赖关系图,其中包括应用程序所需要的每个模块,然后将这些模块打包成bundle由浏览器加载,通常只有一个。

首先我们先理解四个概念:

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

如上,我们通过output.filenameoutput.path告诉了bundle的名称和以及要生成到哪里。

//webpack.config.js
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: /\.txt$/, use: 'raw-loader' }
    ]
  }
};

module.exports = config;

以上配置中,对一个单独的 module 对象定义了 rules 属性,里面包含两个必须属性:test 和 use。这告诉 webpack 编译器(compiler) 如下信息:

“嘿,webpack 编译器,当你碰到「在 require()/import 语句中被解析为 '.txt' 的路径」时,在你对它打包之前,先使用 raw-loader 转换一下。”

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: /\.txt$/, use: 'raw-loader' }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin(),
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

module.exports = config;
上一篇 下一篇

猜你喜欢

热点阅读