学习笔记 - webpack. How loaders are used in webpack?

https://webpack.js.org/concepts/#entry
ref: https://webpack.js.org/concepts/loaders/
其实就是整理了一下官方文档,加深理解和印象…

1. Webpack:

1.1 Concept

  • webpack就是个打包机:
    Webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.

1.2 Core Concept

Entry, Output, Loaders, Plugins, Mode, Browser Compatibility

1.2.1 Entry

An entry point indicates which module webpack should use to begin building out its internal dependency graph. webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly).

webpack.config.js

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

1.2.2 Output

The output property tells webpack where to emit the bundles it creates and how to name these files. It defaults to ./dist/main.js for the main output file and to the ./dist folder for any other generated file.

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'
  }
};

1.2.3 Loaders

webpack only understands JavaScript and JSON files. Loaders allow webpack to process other types of files and convert them into valid modules that can be consumed by your application and added to the dependency graph.

At a high level, loaders have two properties in your webpack configuration:

  1. The test property identifies which file or files should be transformed.
  2. The use property indicates which loader should be used to do the transforming.

webpack.config.js

const path = require('path');

module.exports = {
  output: {
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
      // "Hey webpack compiler, when you come across a path that resolves to a '.txt' file 
      // inside of a require()/import statement, use the raw-loader to transform it before 
      // you add it to the bundle."
    ]
  }
};

1.2.4 Plugins

loaders: transform certain types of modules
plugins: wider range of tasks (bundle optimization, asset management, injection of environment variables…)

In order to use a plugin, you need to require() it and add it to the plugins array

webpack.config.js

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

module.exports = {
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'}) // Since you can use a plugin multiple times in a configuration for different 
    // purposes, you need to create an instance of it by calling it with the new operator.
  ]
};

1.2.5 Mode

By setting the mode parameter to either development, production or none, you can enable webpack’s built-in optimizations that correspond to each environment. The default value is production.

module.exports = {
  mode: 'production'
};

1.2.6 Browser Compatibility

webpack supports all browsers that are ES5-compliant (IE8 and below are not supported). webpack needs Promisefor import() and require.ensure()

2. Loaders

  • Allow you to pre-process files as you import or load, loaders are kind of like tasks, providing a powerful way to handle front-end build steps.
  • Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs. Loaders even allow you to do things like import CSS files directly from your JavaScript modules!

1.1 Example

To use loaders that tell webpack to load a CSS file or to convert TypeScript to JavaScript:

  1. install the loaders you need
npm install --save-dev css-loader ts-loader
  1. And then instruct webpack to use the css-loader for every .css file and the ts-loader for all .ts files:

webpack.config.js

module.exports = {
  module: {
    rules: [
      { test: /\.css$/, use: 'css-loader' },
      { test: /\.ts$/, use: 'ts-loader' }
    ]
  }
};

2. Use Loaders

Three ways to use loaders in your application:

  1. Configuration (recommended): Specify them in your webpack.config.js file.
  2. Inline: Specify them explicitly in each import statement.
  3. CLI: Specify them within a shell command.
  • Configuration
module.exports = {
  module: { // module.rules allows you to specify several loaders within your webpack configuration.
    rules: [
      {
        test: /\.css$/,
        use: [
          // style-loader
          { loader: 'style-loader' },
          // css-loader
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          },
          // sass-loader
          { loader: 'sass-loader' }
        ]
      }
    ]
  }
};

Loaders are evaluated/executed from right to left (or from bottom to top). In the example below execution starts with sass-loader, continues with css-loader and finally ends with style-loader.

  • Inline
import Styles from 'style-loader!css-loader?modules!./styles.css';
import Styles from '!style-loader!css-loader?modules!./styles.css';
import Styles from '!!style-loader!css-loader?modules!./styles.css';
import Styles from '-!style-loader!css-loader?modules!./styles.css';

-CLI

webpack --module-bind pug-loader --module-bind 'css=style-loader!css-loader'

This uses the pug-loader for .jade files, and the style-loader and css-loader for .css files.

3. Loader Features

  1. Chianed: webpack expect javascript
loader_1: transform
...
loader_n: transform
Javascript
  1. Loaders can be synchronous or asynchronous.
  2. Loaders run in __Node.js __and can do everything that’s possible there.
  3. Loaders can be configured with an options object (using query parameters to set options is still supported but has been deprecated).
  4. Normal modules can export a loader in addition to the normal main via package.json with the loader field.
  5. Plugins can give loaders more features.
  6. Loaders can emit additional arbitrary files.

4. Resolving Loaders

  • In most cases it will be loaded from the module path (think npm install, node_modules).
  • A loader module is expected to export a function and be written in Node.js compatible JavaScript; Most commonly managed with npm, but you can also have custom loaders as files
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值