乐趣区

nodejs-servicewebpack打包-koa服务

前言

目前前端更新迭代越来越快,相应的配套服务也跟着快速发展,node service koa 使用 webpack 打包方案

安装

npm install
npm run build
  1. 新建项目 package.json
{
  "name": "koa2-blog",
  "version": "1.0.0",
  "description": "blog",
  "main": "main.js",
  "directories": {"lib": "./src/main.js"},
  "scripts": {
    "dev": "supervisor -w src src/main.js",
    "build": "webpack --progress --hide-modules --config webpack.config.js",
    "test": "./node_modules/mocha/bin/mocha --harmony test"
  },
  "author": "Jiang Xiao Er",
  "license": "MIT",
  "dependencies": {"config-lite": "^2.0.0",},
  "devDependencies": {
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-minify-webpack-plugin": "^0.3.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    "clean-webpack-plugin": "^0.1.17",
    "crypto": "^1.0.1",
    "express": "^4.17.1",
    "fs": "^0.0.1-security",
    "mocha": "^4.0.1",
    "path": "^0.12.7",
    "webpack": "^3.10.0",
    "webpack-node-externals": "^1.7.2"
  }
}
  1. webpack.config.js
/**
 * Created by Jiang Xiao Er 2019/7/10.
 * 
 * 
 */
'use strict';
const webpack = require('webpack');
const path = require('path');
const cleanWebpackPlugin = require('clean-webpack-plugin');
var nodeExternals = require('webpack-node-externals');
const MinifyPlugin = require('babel-minify-webpack-plugin');
module.exports = {entry: path.resolve(__dirname, 'service.js'), // 入口文件
    output: {path: path.resolve(__dirname), // 输出路径
        filename: 'app.js'             // 输出项目根目录
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            use: [{
                loader: 'babel-loader',
                options: {presets: ['es2015', 'stage-3'] // 兼容 es6,并添加.babelrc
                }
            }]

        }]
    },
    target: 'node', // 服务端打包
    externals: [nodeExternals()], //node 打包可去除一些警告
    resolve: {
        modules: [
            'node_modules',
            path.resolve(__dirname, 'src')
        ]
    },
    plugins: [new cleanWebpackPlugin(['app.js'], {root: path.resolve(__dirname, './')
        }),
        new MinifyPlugin() // 压缩 js]
};
  1. ES6 语法支持

修改项目中的 .babelrc 文件

{
 "presets": [
    "es2015",
    "stage-3"
 ],
 "plugins" : ["transform-runtime"]
}
  1. service.js
const $ = require('jquery')
console.log("Hello Word,hi jquery")
console.log("hi jquery",$)

$ npm run build
$ node app.js

项目地址 https://github.com/shanyanwt/…

问题

因为是基于 node 环境下打包,其实 webpack 并没有把项目中的 node_modules 打入 app.js 说以执行 app.js 的前提下需要在该项目录下执行,webpack 打包只是吧 多文件整合到一个文件中,并没有项目依赖,在服务其中还需要重新 npm install,如果一天也可以像打 web 项目一样吧依赖打入文件和 java 生成编译后的 jar 执行文件,这样生产环境也就省去一些不必要的环节。

如果你有好的建议和想法可以在评论区留言,或者邮箱联系: shanyanwt@163.com
愿你保持独立思考、不卑、不亢、不怂努力长成自己喜欢的样子

我是一只孤独的狼 …… 欢迎 star

退出移动版