webpack打包nodejs

前言

本文将简单介绍如何使用webpack编译构建nodejs项目。

1. 安装依赖

1.1 安装webpack

npm install --save-dev webpack@4 webpack-cli@3
npm install -g webpack-cli@3

1.2 其他依赖包

主要是webpack插件

{
  "devDependencies": {
    "@babel/plugin-transform-modules-commonjs": "^7.15.4",
    "@babel/plugin-transform-runtime": "^7.15.0",
    "@babel/preset-env": "^7.4.4",
    "@babel/preset-typescript": "^7.14.5",
    "@babel/runtime": "^7.15.4",
    "babel-loader": "^8.0.5",
    "clean-webpack-plugin": "^3.0.0",
    "cross-env": "^7.0.3",
    "friendly-errors-webpack-plugin": "^1.7.0",
    "terser-webpack-plugin": "^3.0.1",
    "ts-loader": "^8.3.0",
    "ts-node": "^10.2.1",
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.11"
  }
}

2. 执行构建

本小节将介绍webpack构建的执行步骤。

2.1 新建 webpack.config.js配置文件

// webpack.config.js

const path = require('path')
const os = require('os')
const TerserPlugin = require('terser-webpack-plugin')
const webpack = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin')
const projectPath = process.cwd()
const srcDirPath = path.resolve(__dirname, 'src')
const nodeModulesPath = path.resolve(__dirname, 'node_modules')

module.exports = {
  devtool: 'none',
  target: 'node',
  mode: 'none',
  context: path.resolve(projectPath),
  mode: process.env.NODE_ENV,
  entry: path.resolve(projectPath, 'src/main.js'),
  output: {
    filename: 'main.js',
    path: path.join(projectPath, 'dist')
    libraryTarget: 'commonjs2',
  },
  resolve: {
    alias: {
      '@': srcDirPath,
    },
    extensions: ['.ts', '.js'],
    mainFiles: ['index'],
    modules: [srcDirPath, nodeModulesPath],
  },
  performance: {
    hints: false,
  },
  stats: (() => {
    return {
      warnings: false,
      assets: true,
      assetsSort: '!size',
      cached: true,
      builtAt: true,
      cachedAssets: true,
      children: true,
      chunksSort: '!size',
      chunkGroups: true,
      chunkModules: true,
      chunkOrigins: true,
      chunks: true,
      colors: true,
      depth: true,
      entrypoints: true,
      env: true,
      errorDetails: true,
      errors: true,
    }
  })(),
  optimization: {
    runtimeChunk: false,
    minimizer: [
      // 丑化代码
      new TerserPlugin({
        test: /\.js$/i,
        parallel: os.cpus().length,
        sourceMap: true,
        extractComments: false,
        terserOptions: {
          ecma: 5,
          warnings: false,
          parse: {},
          compress: {},
          mangle: true,
          keep_classnames: false,
          keep_fnames: false,
          output: {
            beautify: false,
            comments: false,
            // 只用单引号
            quote_style: '1',
          },
        },
      }),
    ],
  },
  plugins: [
  	// 控制台输出信息
    new FriendlyErrorsWebpackPlugin({
      compilationSuccessInfo: {
        messages: [],
        notes: [],
      },
      clearConsole: true,
    }),
    // 忽略某些模块的转换操作
    new webpack.IgnorePlugin({
      checkResource(resourcePath) {
        return false
      },
    }),
    // 清理资源
    new CleanWebpackPlugin({
      verbose: true,
      cleanStaleWebpackAssets: false,
      cleanOnceBeforeBuildPatterns: ['**/*'],
    }),
  ],
  module: {
    rules: [
      // 增加对 typescript 的支持
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: { appendTsSuffixTo: [/\.vue$/] },
        exclude: /node_modules/,
      },
      // 转换 es6 到 es5
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
    ],
  },
}

2.2 配置打包命令

{
  "scripts": {
    "watch": "cross-env npx webpack --config webpack.config.js --watch --devtool source-map --mode development",
    "build": "cross-env npx webpack --config webpack.config.js --mode production"
  },
}

2.3 执行打包操作

  • 开发环境:npm run watch
  • 生产环境:npm run build
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿祥_csdn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值