This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

Webpack packaging TS

Many front-end friends know what WebPack is. Webpack is a module packager. Its primary goal is to package JavaScript files together for use in the browser.

Webpack concept

Essentially, WebPack is a static module packaging tool for modern JavaScript applications. When WebPack processes an application, it builds a dependency graph internally that maps to each module required by the project and generates one or more bundles

Packaging cause

During the process of writing ts files, export may be used to avoid naming conflicts.

When writing code in a new TypeScript file, it is in the global namespace, and using the global variable space is dangerous because it conflicts with the code names in the file

So you can use import or export to create a local scope in the current file

// Use export to create a local scope in the current file to prevent variable conflicts
export{}Copy the code

But when I run the command TSC tsc05.ts -w to generate a JS file that is imported into HTML using the

In some cases, it is not possible to import the generated JS files directly into the browser, so the usual exercises can be used. If you want to use a formal project, it is better to use a packaging tool such as WebPack to package the generated JS files

The generated tsc05.js file

"use strict";
exports.__esModule = true;
exports.addNum = void 0;
// Declare the function
function abc() {}// Function expression
var def = function () {};// The function has input and output. If TS is a constraint, you need to use type definition
function addNum(a, b) {
    if (b)
        return a + b;
    else
        return a;
}
exports.addNum = addNum;
console.log(addNum(1));
Copy the code

Unexpected token ‘export’ : Uncaught SyntaxError: Unexpected token ‘export’

Since the browser does not support exports, I used Webpack to package the TS file here




Install webpack

Webpack is installed for ts compilation and running. There are many versions of WebPack. If you install webPack by default, it is usually the latest version

The installation method I use is YARN installation, of course, you can also directly use NPM or CNPM to install, are relatively simple

Yarn add webpack webpack-cli

In the basic configuration, WebPack only works with JS, so we need to convert TS to JS, using the TS-Loader package

Command: yarn add ts-loader

Install typescript, which is definitely required

Command: yarn add typescript

Note: typescript can be installed globally or locally. Try installing with ‘yarn add typescript’ or ‘NPM install’ Typescript ‘. If typescript is installed globally, try using ‘YARN link typescript’ or’ NPM link typescript’.” Cannot load type script. Try to install using the Add Type script or the NPM Install type script. If TypeScript is installed globally, try using “link TypeScript” or “NPM link TypeScript.”

Current configuration in package.json:

{
  "devDependencies": {
    "babel-preset-es2015": "^ 6.24.1"."babel-register": "^ 6.26.0"
  },
  "dependencies": {
    "@types/node": "^ 16.4.12." "."body-parser": "^ 1.19.0"."express": "^ 4.17.1"."inquirer": "^ 8.1.2"."ts-loader": "^ 9.2.5." "."typescript": "^ 4.3.5." "."webpack": "^ 5.48.0"."webpack-cli": "^ 4.7.2." "."webpack-dev-server": "^ 3.11.2"}}Copy the code




Write the WebPack configuration

webpack.config.js

With these packages installed, you need to configure the webpack.config.js file

It is important to create the webpack.config.js file in the same directory as package.json, which is the webPack configuration file

const path = require('path');   
const webpack = require('webpack');
module.exports = {
  entry:'./TypeScript/tsc05.ts'.// Package the entry file, expect to package the entry file. This is the location of tSC05.ts
  output: {filename:'tsc05.js'.// Output the name of the file
    path:path.resolve(__dirname,'./TypeScript/')  // Get the output path
  },
  mode: 'development'.// The whole mode can not be used, the mode is production environment is compressed good, here configure development environment convenient to see the generated code
  module: {rules: [{
      test: /\.tsx? $/,
      use: 'ts-loader'.exclude: /node_modules/}},resolve: {
    extensions: ['.ts']      // Parse the file format}},Copy the code

Script script

Configure the script script in package.json to run WebPack

"scripts": {
    "dev": "webpack --mode development".// NPM run dev Package once
}
Copy the code

Use NPM run dev to package once and succeed.

The entry entry file tsc05.ts, which needs to be configured in the corresponding webpack.config.js file, already exists

The export file tsc05.js is generated after the tsc05.ts file is packaged




The final results

Import the tsc05.js file from webPack into HTML

It has been found to run successfully

The configuration process here is simple, but if you add webPack-packed hot updates to it, you might get configuration errors