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

(译文)开始学习Webpack-应用TypeScript,配置热加载和SourceMap

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

项目初始化:采用TypeScript

我们的版本是:

$ node --version
v8.5.0
$ npm --version
5.5.1

npm版本升级了,因为npm最近带来了新特性,本地会生成package-lock.json,能
提高一些性能,想知道更多的,可以google一下。

创建目录初始结构:

$ mkdir pickle
$ cd pickle
$ touch index.html
$ touch index.ts
$ touch webpack.config.js

初始化package.json

$ npm init --force
Wrote to /Users/abraham/dev/pickle/package.json:
...

--force是告诉自动采用默认配置。
安装相应的包:

$ npm install --save-dev typescript ts-loader webpack http-server
+ [email protected]
+ [email protected]
+ [email protected]
+ [email protected]
added 394 packages in 17.115s

创建tsconfig.json文件:(这里采用本地的typescript包,你也可以全局安装)

$ ./node_modules/typescript/bin/tsc --init
message TS6071: Successfully created a tsconfig.json file.

webpack.config.js:

const path = require('path');
module.exports = {
  entry: './index.ts',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: [ ".tsx", ".ts", ".js" ]
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

修改pacakge.json:

{
  ...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "serve": "http-server"
  },
  ...
}

然后你跑如下命令,可以看到:

$ npm run build
> [email protected] build /Users/abraham/dev/pickle
> webpack
ts-loader: Using [email protected] and /Users/abraham/dev/pickle/tsconfig.json
Hash: 8b5d98f242aeda6844bb
Version: webpack 3.6.0
Time: 815ms
    Asset Size Chunks Chunk Names
bundle.js 2.51 kB 0 [emitted] main
   [0] ./index.ts 14 bytes {0} [built]

修改index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Pickle</title>
</head>
<body>
  <h1>Welcome to Pickle</h1>
  <label for="color-picker">Select a new background color</label>
  <input >
  <script defer src="dist/bundle.js"></script>
</body>
</html>
class Pickle {
  constructor(private picker: Element, private background: HTMLElement) {
    picker.addEventListener('change', this.colorChange.bind(this), false);
    this.background = background;
  }
  colorChange(event: Event): void {
    // `<HTMLInputElement>` tells TypeScript what type `target` is so that it knows there is a `value` property available.
    let input = <HTMLInputElement>event.target;
    this.background.style.backgroundColor = input.value;
  }
}
let picker = document.querySelector('#color-picker');
// The if avoids TypeScript complaining that `picker` might be null.
if (picker) {
  new Pickle(picker, document.body);
}

然后运行:

$ npm run build
...
$ npm run serve
> http-server
Starting up http-server, serving ./
Available on:
  http://127.0.0.1:8080
  http://192.168.200.8:8080
Hit CTRL-C to stop the server

浏览器访问:http://127.0.0.1:8080

webpack热加载配置(修改代码,自动刷新代码)

我们的package.json的script长这样:

{
  ...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "serve": "http-server",
    "watch": "webpack --watch"
  },
  ...
}

运行npm run watch后是这样:

$ npm run watch
> [email protected] watch /Users/abraham/dev/pickle
> webpack --watch
Webpack is watching the files…
ts-loader: Using [email protected] and /Users/abraham/dev/pickle/tsconfig.json
Hash: 16fb35ccc9f9b3f14c5d
Version: webpack 3.8.1
Time: 957ms
    Asset Size Chunks Chunk Names
bundle.js 3.27 kB 0 [emitted] main
   [0] ./index.ts 775 bytes {0} [built]

当然我们可以直接合并命令:

{
  ...
  "serve": "npm run watch & http-server"
  ...
}

然后直接运行npm run serve就行了。Webpack会自动监听和编译我们的代码。
进一步,我们希望支持Hot Module Replacement(支持模块级别的自动刷新,而不需要刷新浏览器),
需要安装如下两个东西:

$ npm install --save-dev webpack-dev-server
+ [email protected]
added 165 packages in 10.49s
$ npm install --save-dev html-webpack-plugin
+ [email protected]
added 38 packages and removed 11 packages in 4.662s

修改配置webpack.config.js:

module.exports = {
  ...
  devServer: {
    contentBase: path.resolve(__dirname, '.') ,
    hot: true
  }
  ...
};

依赖它们:

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

添加插件:

module.exports = {
  ...
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html'
    }),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ]
  ...
};

HotModuleReplacementPlugin 插件是告诉我们用热加载
NamedModulesPlugin 是用来清空编译日志的,这样只会显示我们入口文件信息。
HtmlWebpackPlugin 会把根目录的template文件(index.html),输出到dist目录的filename指定的文件名。这样webpack可以自动在index.html里面添加script标签,所以我们的index.html里面不需要: <script defer src="dist/bundle.js"></script>

修改package.json:

{
  ...
  "serve": "webpack-dev-server --open"
  ...
}

--open告诉webpack在浏览器打开我们的页面。
运行npm run serve就行了。大功告成。

webpack支持source maps

修改tsconfig.json:、

{
  ...
  "sourceMap": true,
  ...
}

修改webpack.config.js:

module.exports = {
  ...
  devtool: 'eval-source-map'
};

以上就是今天的内容,不知道你学会了webpack配置,TypeScript会用了吗?
原文链接:https://bendyworks.com/blog/getting-started-with-webpack-source-maps

作者知乎/公众号:前端疯 (一群热爱前端的一线程序员维护,想要用前端改变世界。)


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
React之hook/class结合typescript笔记发布时间:2022-07-18
下一篇:
TypeScript-基础类型发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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