zoukankan      html  css  js  c++  java
  • (译文)开始学习Webpack-应用TypeScript,配置热加载和Source Map

    项目初始化:采用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
    + typescript@2.5.2
    + ts-loader@2.3.7
    + webpack@3.6.0
    + http-server@0.10.0
    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
    > pickle@1.0.0 build /Users/abraham/dev/pickle
    > webpack
    ts-loader: Using typescript@2.5.2 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 id="color-picker" type="color" value="#2196F3">
      <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
    > pickle@1.0.0 watch /Users/abraham/dev/pickle
    > webpack --watch
    Webpack is watching the files…
    ts-loader: Using typescript@2.5.3 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
    + webpack-dev-server@2.9.2
    added 165 packages in 10.49s
    $ npm install --save-dev html-webpack-plugin
    + html-webpack-plugin@2.30.1
    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

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

  • 相关阅读:
    U盘安装CentOS 7系统
    生产库中遇到mysql的子查询
    mysql 储存类型自增主键区别
    MySQL主从数据库同步延迟问题解决
    MySQL 加锁处理分析
    120篇精华文章打包送,干货慎入!
    mysql批量删除相同前缀的表和修改表名
    用pt-online-schema-change给大表在线加字段的时候导致从库数据丢失的问题
    【MySQL】online ddl 工具之pt-online-schema-change
    互联网公司为啥不使用mysql分区表?
  • 原文地址:https://www.cnblogs.com/xunxing/p/4813e5f34e44f20fa747acbfe2516af2.html
Copyright © 2011-2022 走看看