koa項目熱更新和es6語法兼容

熱更新很簡單,須要使用到nodemon。node

用法以下:webpack

npm i nodemon -D
// package.json
"scripts": {
    "start": "nodemon src/index.js"
  },

而後運行npm run startes6

es語法支持
這裏須要用到以下插件:web

webpack & webpack-cli
clean-webpack-plugin: 清除dist目錄
webpack-node-externals: 不對node_modules進行處理
@babel/core: es6支持
@babel/node: 調試使用
@babel/preset-env: 新語法的支持
babel-loader
cross-env: 環境變量的處理npm

webpack.config.js 配置以下:json

const path = require('path');
var nodeExternals = require('webpack-node-externals');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const webpackconfig = {
  target: 'node',
  mode: 'development',
  entry: {
    server: path.join(__dirname, 'src/index.js')
  },
  devtool: 'eval-source-map',
  output: {
    filename: '[name].bundle.js',
    path: path.join(__dirname, './dist')
  },
  module: {
    rules: [
      {
        test: /\/(js|jsx)$/,
        use: {
          loader: 'babel-loader'
        },
        exclude: [path.join(__dirname, '/node_modules')]
      }
    ],
    },
    externals: [nodeExternals()],
    plugins: [
      new CleanWebpackPlugin()
    ],
    node: {
      console: true,
      global: true,
      process: true,
      Buffer: true,
      __filename: true,
      __dirname: true,
      setImmediate: true,
      path: true
    }
  }
module.exports = webpackconfig

.babelrc 配置以下:babel

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}

而後執行以下命令:ui

npx babel-node src/index.jsspa

就可使用import 語法了。插件

固然,我還想結合使用熱更新怎麼辦呢?

"scripts": {
    "start": "nodemon src/index.js",
    "start:es6": "nodemon --exec babel-node src/index.js"
  },

image.png

相關文章
相關標籤/搜索