Why does Webpack need Loader

Webpack only understands JavaScript and JSON. Loader enables WebPack to handle other types of file languages and convert them to modules recognized by WebPack for use by applications

Initialize the project?

After mkdir loader-example, NPM init -y in this directory generates the default package.json file in which you can configure the package command

"scripts": {
  "build": "webpack serve"
  "build": "webpack"
}
Copy the code

The root directory creates webpack.config.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development'.// First set to development, no compression code, easy debugging
  entry: {
    main: './src/index.js'
  },
  output: {
    filename: '[name].js'.path: path.resolve(__dirname, 'dist');
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, './index.html'),  // Create an index. HTML file in the root directory})].devServer: {
    contentBase: path.resolve(__dirname, 'dist'),}}Copy the code

The root directory creates the SRC folder where the index.js file input is created

const content = {{ __content__ }};
console.log(content);
document.getElementsByTagName('body') [0].innerHTML = content
Copy the code

After the dependency is installed, runnpm run dev or run buildThe prompt is wrong

The {{__content__}} module fails to parse, indicating that a loader is required to process this file

Three, make a long time finally start to write Loader?

What is the Loader

First of all, we recommend that you read the webpack website: How to write a Loader?

This function takes a parameter (string or buffer type). This parameter is the source file we need to translate, compile, replace, etc. , and ultimately back to Webpack

Create a loaders folder in the root directory and create replaceloader.js

// Write a loader module that accepts an argument, does nothing, and then returns it
module.exports = function (source) {
	//source Source file content, string or buffer type
	return source;
}
Copy the code

So let’s continue with the above idea

module.exports = function (source) {
	 // Replace source file {{__content__}} with 'iwen'
	const result = source.replace("{{ __content__ }}".JSON.stringify('iwen'));
	return result;
}
Copy the code

Ok, loader is finished, is not very simple, then webpack inside the configuration

  module: {
    rules: [{
      test: /\.js$/,
      use: {
        loader: path.resolve(__dirname, './loaders/replaceLoader.js'),}}},Copy the code

Improve our loader

Loader-utils provides a getOptions method to get the option configuration in the WebPack Loader configuration

const loaderUtils = require('loader-utils');

module.exports = function (source) {
  // Get the options configuration
  const options = loaderUtils.getOptions(this);
  // Go back to options to configure a value parameter
  const { value } = options; 
  // Replace the content of the source file with value
  const result = source.replace("{{ __content__ }}".JSON.stringify(value));
  // This. callback is also an official API that replaces return
  this.callback(null, result);
}
Copy the code

Other loader API

Webpack configures options

 module: {
    rules: [{
      test: /\.js$/,
      use: {
        loader: path.resolve(__dirname, './loaders/replaceLoader.js'),
        options: {
          value: 'iwen' // The parameters are passed to the loader for getOptions to receive}}}},Copy the code

performnpm run dev

A, endnotes

Thank you all for your likes and attention

github example-loader