• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

webpack+typescript入门实例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

使用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:\SPAProjects\webpacktypescript>npx webpack
npx: installed 1 in 11.482s
The "path" argument must be of type string
D:\SPAProjects\webpacktypescript\node_modules\webpack\bin\webpack.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:\SPAProjects\webpacktypescript>npm run build

> [email protected] build D:\SPAProjects\webpacktypescript
> 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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap