Modular practice of front-end Projects 2: Packaging infrastructure Code with Webpack

Source: Internet
Author: User
Tags base64

The following are the practical aspects of the front-end project modularity, including the following:

    1. Build NPM private Warehouse management source and dependence;
    2. Use Webpack to package the infrastructure code;
    3. Writing a reliable class library using TypeScript
    • Benefits of using TypeScript
    • Unit testing using mocha/jest [in implementation]

This article is about the 2nd part of the front-end project templating

Present situation

The actual project is far more complex than the mygreeting used by the example, such as

    • In order to improve maintainability we have broken the project into many functional templates;
    • We want to use Promise and other grammar, but scruples about the supporting ability of the target environment;
    • May rely on a number of third-party class libraries;
    • In order to increase loading speed we need to do a lot of extra work when packing;
      • Code compression;
      • Tree Shaking (at the end of the text);
    • Can be run in a WEB browser, can also be used in NodeJS;

Suppose we have a toolset project Myhammer, which contains the Base64 transformation feature and a simple version of the Dictionary tree implementation, the project structure is as follows:

busybruce@DESKTOP-B8KJKRS /d/Documents/MyGit/PracticeInNPM/myHammer$ tree src/ test/src/├── base64.js├── index.js└── TrieFilter.jstest/├── base64.test.js└── TrieFilter.test.js0 directories, 5 files

index.jsExported the functional modules in the project:

const base64     = require('./base64');const TrieFilter = require('./TrieFilter')module.exports = {    base64,    TrieFilter,}

If not packaged, publishing the current project separately to the NPM warehouse is no problem, just

    1. Rely on the project when the wording of the more tangled, shaped like const base64 = require('myHammer/src/base64') ;
    2. Possible adaptation issues to the target environment, as described earlier;
    • Target environment does not support syntax such as Promise, etc.
    • The source code is coffeescript or TypeScript, cannot be quoted directly

Use Webpack below to resolve these issues.

Webpack Packaging base Class Library

Webpack document content, online tutorials are more about application packaging, is now organized as follows.

This article is not a guide to Webpack, only mentions class library packaging, while the Webpack has been updated to version 4.x.

package.json

The nodes that need to be configured package.json are used by the main NodeJS environment.

"main": "src/index.js",

The NodeJS runtime environment is agreed upon and require('xxx') will be read by the configuration when used.

    1. Avoid the require('myHammer/src/base64') notation of a similar referential full path
    2. If the source uses a high version of the language features, you can translate and package the code into dist/inde-es5.js a path, and then modify the configuration to point to the file to backward compatibility
    3. Use the same language you need to translate into JavaScript

When we look for references in some Ides, we often find that function declarations are implemented in a number of places because the code is translated and packaged into many copies, as shown in.

webpack.config.js

The class library package needs to webpack.config.js output be configured in the following:

output : {  library      : "hammer",  libraryTarget: "umd",  globalObject : "this",  path         : path.join(__dirname, "dist"),  filename     : "hammer.js",}

Other configuration please read the document yourself, the full content of the code webpack.config.js.

    • libraryTarget: In order to be effective in both the browser and NodeJS environment, use umd as a target, refer to Output-librarytarget
    • globalObject: Use this the Replace default window , reference Webpack 4.0.1 | Webworker window is not defined #6642

As mentioned earlier, without regard to language, version, target platform differences, the source code is published directly to the NPM repository, and then added dependencies and references are no problem. In an increasingly complex business situation, handwritten code eliminates these differences directly at the implementation level, and using Webpack allows us to focus more on the business itself, making life easier.

Publish to NPM and use dependencies

After completing the specific business, we package the project and publish it to the private NPM warehouse

webpack --mode development # 视具体需求npm publish --registry http://ubuntu-17:4873 # --force

In the Mydemo project we add references

yarn add myHammer --registry http://ubuntu-17:4873

Modify the index.js following:

const myGreeting = require('myGreeting');const {base64}   = require('myHammer');(function () {    let greeting = myGreeting('Rattz');    console.log(base64.encode(greeting));})();

Run up

$ node index.jsSGVsbG8gUmF0dHo=
About Tree Shaking

Mention a little bit about the tree Shaking, which simply says that tree Shaking can effectively reduce the size of a packaged file by not referencing the code that doesn't depend on it.

For example, we used the ES2016 syntax and wanted to compile it in the ES2015 environment. There are a number of possible options, one of which is

    • Use Babel family barrels included babel-cli, babel-core, babel-loader, babel-preset-env ;
    • Add. babelrc file to write content {"presets":["env"]} ;
    • Used in the first line of the ingress coderequire('babel-polyfill');

Babel syntax conversion, patch files for the adaptation of the lower version of ES2015, the scheme babel-polyfill is fully referenced, the package is completed after the use of about 120k size, often more than the business code.

The tree Shaking is to solve the problem, for example, a template provides addition and subtraction, and we rely only on the addition method, if the packaging tool supports Tree Shaking, it can be packaged to eliminate unused subtraction related code.

Webpack provides support, seen in Tree Shaking-webpack.
The source code used for the project has been released GITHUB,JUSFRW original

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.