搭建webpack + typescript 开发环境,开启愉快开发之旅 – Falost的小窝
  • 欢迎关注我的微信公众号“ frontEnd_Developer ” 右边扫描关注 --->>

搭建webpack + typescript 开发环境,开启愉快开发之旅

Code Log 神棍 60℃ 0评论

最近在使用TypeScript ,越用越爽,就是有些包不支持,但是还是不影响我的使用,分享下我的开发环境吧!

环境

  • webpack
  • typescript

依赖

  • babel
  • babel-loader
  • babel-polyfill
  • babel-preset-env
  • ts-loader
  • typescript
  • uglifyjs-webpack-plugin
  • webpack
  • webpack-dev-server
  • webpack-merge
  • clean-webpack-plugin
  • copy-webpack-plugin
  • ....

入口

index.html

<!DOCTYPE html>
<html>
<head>
    <title>hello</title>
    <script src="/index.js" type="text/javascript"></script>
</head>
<body>
    <div id="app"></div>
</body>
</html>

package.json

{
  "name": "typescript study",
  "version": "1.0.0",
  "description": "hello ts",
  "main": "index.js",
  "scripts": {
    "start": "npm run dev",
    "compress": "node build/compress.js",
    "dev": "webpack-dev-server --client-log-level none --color --inline --hot --config build/webpack.dev.js",
    "build": "webpack --config webpack.prod.js --progress --color"
  },
  "author": "falost",
  "license": "ISC"
    .....
}

tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true,
    "allowJs": true,
    "module": "commonjs",
    "removeComments": true,
   // 可以使用 Promise, async, await等新语法
    "target": "es2017"
  }
}

.babelrc

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "safari >= 7"]
      }
    }]
    ["es2015", { "modules": false }],
    "stage-2"
  ],
  "plugins": [
    "transform-decorators-legacy"
  ]
}

build/webpack.base.conf.js

const config = require('../config')
const path = require('path')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}
module.exports = {
  //页面入口文件配置
  entry: {
    // index: './src/index.js',
    index: ["babel-polyfill", "./src/ts/main.ts"]
  },
  //编译输出配置
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.ts', '.js', '.json']
  },
  module:{
    //模块加载器
    rules:[
      {
        test:/\.js$/,
        loaders:['babel-loader?presets[]=es2015'],
        exclude:/node_modules/
      },
      {
        test:/\.(css|sass|scss)$/,
        loaders:['style-loader', 'css-loader', 'sass-loader', 'postcss-loader', 'autoprefixer-loader'],
        include: [resolve('src')]
      }
    ]
  }
}

build/webpack.dev.js

process.env.NODE_ENV = 'development';

const path = require('path');
const config = require('../config');
const merge = require('webpack-merge');
const CopyWebpackPlugin = require('copy-webpack-plugin')
// 引入通用webpack配置文件
const common = require('./webpack.base.conf')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
module.exports = merge(common, {
  module: {
    rules:
      [
        {
          test: /\.tsx?$/,
          loader: 'ts-loader'
        },
      ]
  },
  // 使用 source-map
  devtool: config.dev.devtool,
  // 对 webpack-dev-server 进行配置
  devServer: {
    clientLogLevel: 'warning',
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    contentBase: config.dev.assetsPublicPath,
    // 设置localhost端口
    port: config.dev.port,
    // 自动打开浏览器
    open: config.dev.autoOpenBrowser,
  },
  plugins: [
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
});

build/webpack.prod.js

process.env.NODE_ENV = 'production';

const path = require('path');
const merge = require('webpack-merge');
// 引入通用webpack配置文件
const common = require('./webpack.base.conf');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
//清除输出目录,免得每次手动删除
const CleanWebpackPlugin = require('clean-webpack-plugin');
// 对babel的配置,内容同.babelrc文件
const babelOptions = {
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "safari >= 7"]
      }
    }]
  ]
}
module.exports = merge(common, {
  module: {
    rules: [{
      test: /\.ts(x?)$/,
      exclude: /node_modules/,
      use: [
        {
          loader: 'babel-loader',
          options: babelOptions
        },
        {
          loader: 'ts-loader'
        }
      ]
    }]},
  devtool: 'cheap-module-source-map',
  plugins: [
    new CleanWebpackPlugin(['dist']),
    // 对js代码进行混淆压缩的插件
    new uglifyjsWebpackPlugin({
      uglifyOptions: {
        compress: {
          warnings: false,
          dead_code: process.env.NODE_ENV === 'development' ? false : true , // 移除没被引用的代码
          drop_debugger: process.env.NODE_ENV === 'development' ? false : true, // 移除项目中的debugeer
          drop_console: process.env.NODE_ENV === 'development' ? false : true // 移除console.*的方法
        }
      }
    })
  ],
  // 设置出口文件地址与文件名
  output: {
    path: path.resolve('dist'),
    filename: 'bundle.min.js'
  },
});

config/index.js

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},

    // Various Dev Server settings
    host: '0.0.0.0', // can be overwritten by process.env.HOST
    port: 8081, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,

    useEslint: false,
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    devtool: 'cheap-module-eval-source-map',

    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    productionSourceMap: false
    devtool: '#source-map'
  }
}

到此环境基本配置完成
就可以执行

npm run dev // 进入开发模式
npm run build // 进入打包模式

然后开始酸爽typescript之旅,祝愉快!

初次开始使用ts,如果这当中如有不对之处,望留言多多指教!

转载请注明:Falost的小窝 » 搭建webpack + typescript 开发环境,开启愉快开发之旅

如果你觉得这篇文章不错或者对你有帮助,想请我喝一杯咖啡,可以打赏
喜欢 (1)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址