webpack+typescript入门实例

使用npm 安装相应的模块

webpack 4 需要安装 webpackwebpack-cli 和 typescript 等必要的模块。为了使用 webpack 处理 typescript,还需要 ts-loader
在VSCode的终端输入以下命令

1、初始化项目:

npm init

回答一系列的问题(也可以直接回车使用默认值)后,在当前项目文件夹中会出现一个package.json的配置文件。文件内容大概如下所示:

{
  "name": "webpacktypescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "ts-loader": "^4.2.0",
    "typescript": "^2.8.1",
    "webpack": "^4.6.0",
    "webpack-cli": "^2.0.14"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

2、安装需要的各个模块:

npm install webpack webpack-cli typescript ts-loader --save-dev

3、手动添加 TypeScript 的配置文件 tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

4、添加index.html及默认的 src/index.js文件

在项目文件夹中添加html文件,并命名为:'index.html',并编辑文件内容如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TypeScript + Webpack 4</title>
</head>
<body>

<script src="dist/main.js"></script>
</body>
</html>

5、在项目文件夹中添加名字为src的文件夹,并在该文件夹中添加名字为index.js的JavaScript文件,文件内容如下所示:

console.log("Hello TypeScript!");

完成以上操作后项目的结构如下所示:

webpackwithtypescript
  |- src
    |- index.js
  |- index.html
  |- package.json
  |- package-lock.json
  |- tsconfig.json

6.使用webpack-cli打包项目,输入以下命令:

npx webpack

其中npx详解请参照:https://www.cnblogs.com/vickylinj/p/12228834.html

执行后控制台显示内容如下所示:

D:SPAProjectswebpacktypescript>npx webpack
npx: installed 1 in 11.482s
The "path" argument must be of type string
D:SPAProjectswebpacktypescript
ode_moduleswebpackinwebpack.js
Hash: 7dffdd50a425c0f906c2
Version: webpack 4.6.0
Time: 579ms
Built at: 2018-04-18 14:23:26
  Asset       Size  Chunks             Chunk Names
main.js  577 bytes       0  [emitted]  main
Entrypoint main = main.js
[0] ./src/index.js 33 bytes {0} [built]

7、打包成功,项目文件夹中会多出 dist/main.js 

这也正是 webpack 4 未指定输出文件时默认的位置。此时在浏览器中打开index.html,并在浏览器中按下F12,进入控制台将会看到 consolr.log() 语句的输出结果。

此时的项目文件夹结构:

 webpackwithtypescript
    |- dist
       |- main.js
    |- src
       |- index.js
    |- index.html
    |- package.json
    |- package-lock.json
    |- tsconfig.json

webpack 4 没有配置文件时,使用src/index.js作为默认入口,同时使用dist/main.js作为默认出口。
由于TyepScript文件的默认扩展名为.ts,所以并不适合于没有配置文件的默认状况。

8、webpack 配置文件

在项目文件夹中添加名为webpack.config.js的JavaScript文件,并编辑其内容如以下所示:

const path = require('path');

module.exports = {
    mode: 'development',

    entry: './src/index.ts',
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'dist')
    },

    module: {
        rules: [{
            test: /.ts$/,
            use: "ts-loader"
        }]
    },
    resolve: {
        extensions: [
            '.ts'
        ]
    }
};

9、同时修改package.json如以下内容所示:

{
  "name": "webpacktypescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "ts-loader": "^4.2.0",
    "typescript": "^2.8.1",
    "webpack": "^4.6.0",
    "webpack-cli": "^2.0.14"
  },
  "devDependencies": {},
  "scripts": {
    "build": "webpack",   //添加这一行
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

10、完成以上的设置,然后将src/index.js改名为src/index.ts

webpackwithtypescript
    |- dist
       |- main.js
    |- src
       |- index.ts
    |- index.html
    |- package.json
    |- package-lock.json
    |- tsconfig.json

11、使用npm run build命令编译、打包src/index.ts文件:

D:SPAProjectswebpacktypescript>npm run build

> webpacktypescript@1.0.0 build D:SPAProjectswebpacktypescript
> webpack

Hash: 9bf0b33a5a6b242a917e
Version: webpack 4.6.0
Time: 1683ms
Built at: 2018-04-18 15:03:36
  Asset      Size  Chunks             Chunk Names
main.js  2.84 KiB    main  [emitted]  main
Entrypoint main = main.js
[./src/index.ts] 35 bytes {main} [built]

在控制台窗口可以输入npm run build指令进行打包时,项目中src文件夹中的ts文件index.ts被编译,并输出为 dist/main.js

 12、输出文件名使用hash值

详情参照output.filename的解释

12.1、修改index.html模板,删除script节点

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TypeScript + Webpack 4</title>
</head>
<body>

</body>
</html>

12.2、修改webpack.config.js

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

module.exports = {
    mode: 'development',

    entry: './src/index.ts',
    output: {
        filename: '[hash].js',//main.s=>[hash].js
        path: path.resolve(__dirname, 'dist')
    },

    module: {
        rules: [{
            test: /.ts$/,
            use: "ts-loader"
        }]
    },
    resolve: {
        extensions: [
            '.ts'
        ]
    },
//新增配置,根据html模板自动生成带hash名script的html文件 plugins:[
new HtmlWebpackPlugin({ filename: path.resolve(__dirname, './dist/index.html'), template: 'index.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }) ] };

12.3、build控制台输出结果

Hash: 3003e0c5c17280f9a87b
Version: webpack 4.41.5
Time: 1038ms
Built at: 2020-01-22 11:25:39
                  Asset       Size  Chunks                         Chunk Names
3003e0c5c17280f9a87b.js   3.81 KiB    main  [emitted] [immutable]  main
             index.html  185 bytes          [emitted]
Entrypoint main = 3003e0c5c17280f9a87b.js
[./src/index.ts] 35 bytes {main} [built]
Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [./node_modules/html-webpack-plugin/lib/loader.js!./index.html] 360 bytes {0} [built]
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
        + 1 hidden module

12.4、build文件输出结果(js文件的hash值与12.3输出结果的Hash一致)

index.html:

<!DOCTYPE html><html lang=en><head><meta charset=UTF-8><title>TypeScript + Webpack 4</title></head><body><script type=text/javascript src=3003e0c5c17280f9a87b.js></script></body></html>

参考:https://www.cnblogs.com/yasepix/p/9294499.html

原文地址:https://www.cnblogs.com/vickylinj/p/12228281.html