Compiling js file Babel loader string loader in gulp

Keywords: Webpack npm JSON

js files of ES6 and above can't be executed on some browsers with lower versions, so when the project development is completed, we need to compile js files to translate the syntax of ES6 + into ES5. Here we use gulp's Web pack stream plug-in to package js files. To solve the problem of js translation, we need to use babel. Here we use the babel loader of webpack. See below for specific operation.

webpack-stream

First of all, let's recognize the weback stream. We all know that the function of weback is very powerful, but in the aspect of batch processing, it is still better than gulp. By using weback stream, we can run weback as a "stream" and integrate it into gulp.

1, installation

npm install --save-dev webpack-stream
#Or use yarn installation
yarn add webpack-stream -D

2,webpack.config.js

A simple webpack.config.js file is as follows:

module.exports = {
	mode: "development",
    devtool:"inline-source-map",//Debug tool display
    entry: "./src/js/app.js",
    output: {
        path: "/home/dev/",
        filename: "app.js"
    },
    module:{} //Here is a detailed introduction of this content
}

Configuration item for webpack:

  • Mode, set the environment mode, and tell webpack to use the built-in optimization of the corresponding mode;
    • Development, indicating the development environment;
    • Production, indicating the production environment;
  • devtool, source mapping, can set the code display mode in the browser console;
    • The compiled code content is displayed in the console by default;
    • Source map, display the source code in the console;
    • Inline source map, which means to inline the source map into a file;
  • Entry, an entry file. Multiple entry points can be configured;
    • entry: './path/to/my/entry/file.js', indicating that there is only one entry file;
    • entry: {pageOne:'./src/pageOne/index.js',pageTwo:'./src/pageTwo/index.js'}, set multi page application;
  • Output, the path to export the file. Even if there are multiple entries, only one output configuration can be specified.
    • Path, target output directory, is an absolute path;
    • Filename is the filename of the output file. When there are multiple entry files, use [name] to correspond to the key in the entry;
  • module, which can support various languages and preprocessor writing modules through loader;

3. Import gulpfile.js

Import the webpack.config.js file into gulpfile.js:

const {src,series,dest} = require("gulp");
const webpack = require("webpack-stream");
const webpackConfig = require ("./webpack.config.js");
const path = require("path");

function compileJs() {
	return src("./src/js/**/*.js")
	.pipe(webpackStream(webpackConfig))
	.pipe(dest("./dev/"))
}
exports.default = series(compileJs)

Input the gulp startup service directly in the terminal, and you can see the packed file.

Now we can use web pack stream to package and output js files. However, if we use the syntax of ES2015 + in js, there will be incompatibilities between browsers of lower versions, so we need to compile the packed files. Here we use the following two plug-ins.

babel-loader

Its purpose is to load ES2015 + code, and then translate it into ES5 using Babel.

1, installation

npm install babel-loader @babel/core @babel/preset-env  @babel/plugin-transform-runtime @babel/runtime --save-dev
//Or use yarn installation
yarn add babel-loader @babel/core @babel/preset-env  @babel/plugin-transform-runtime @babel/runtime -D

2, usage

In the webpack configuration object, you need to add Babel loader to the loaders list of the module. You can use the options property to pass options to the loader, as follows:

module: {
    rules: [
        {
            test: /\.js$/, //Files to compile
            exclude: /node_modules/, //Exclude the node modules directory
            use: {
                loader: "babel-loader", //loader name
                options: {	//To configure
                    presets: ['@babel/preset-env'], //Preset
                    plugins: ['@babel/plugin-transform-runtime']//Plug-in unit
                }
            }
        }
    ]
}

3. Precautions

  • Make sure to translate as few documents as possible. You may use /. js $/ to match, which may translate the node ﹐ modules directory or other unnecessary source code. In order to improve the speed of Babel loader, we need to use exclude to exclude the node modules directory;
  • Babel plugin transform runtime is introduced to make all auxiliary code reference from here. It can avoid repeated introduction and reduce code volume;

Click to view A detailed introduction to babel.

string-loader

It is used to convert resource files to strings. Collocation Art template template engine Use together to improve development efficiency.

For example, when we introduce the following html file into the js file, we will automatically change the html file to a string.

import ItemTpl from "../../views/position/position-item.html";

console.log(ItemTpl); //"<html>......</html>"

1, installation

npm install string-loader --save-dev
//Or use yarn to install
yarn add string-loader -D

2, usage

To convert html to a string template:

module: {
    rules: [
        {
          test:/\.html$/,
          loader:"string-loader"
         }
    ]
}

To convert json to a string template:

module: {
    rules: [
        {
          test:/\.json$/,
          loader:"string-loader"
         }
    ]
}

The complete code of compiling js by gulp

So far, by using the two plug-ins Babel loader and string loader, we can translate js files into ES5 syntax compatible with any browser.

The file gulpfile.js is as follows:

const {src,series,dest} = require("gulp");
const concat = require("gulp-concat");
const webpackStream = require("webpack-stream");
const path = require("path");

function compileJs() {
	return src("./src/js/**/*.js")
	   .pipe(webpackStream({
	       mode: "development",
	       devtool:"inline-source-map",
	       entry: {
	           main:"./src/js/app.js",
	           detail:"./src/js/detail.js"
	       },
	       output: {
	           path: path.resolve(__dirname, "./dev/"),
	           filename: "[name].js"
	       },
	       module: {
	           rules: [
	               {
	                   test: /\.js$/,
	                   exclude: /node_modules/,
	                   use: {
	                       loader: "babel-loader",
	                       options: {
	                           presets: ['@babel/preset-env'], //Preset
	                           plugins: ['@babel/plugin-transform-runtime']
	                       }
	                   }
	               },
	               {
	                   test:/\.html$/,
	                   loader:"string-loader"
	               }
	           ]
	       }
	   }))
	   .pipe(dest("./dev/"))
}

exports.default = series(compileJs);
115 original articles published, 41 praised, 20000 visitors+
Private letter follow

Posted by soapsuds on Sat, 14 Mar 2020 21:47:26 -0700