nodejs service,webpack打包 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 文件vue

{
 "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/...java

問題

由於是基於 node環境下打包,其實webpack並無把項目中的 node_modules 打入 app.js 說以執行 app.js 的前提下須要在該項目錄下執行,webpack打包只是吧 多文件整合到一個文件中 ,並無項目依賴,在服務其中還須要從新 npm install ,若是一天也能夠像打web項目同樣吧依賴打入文件和java 生成編譯後的 jar執行文件,這樣生產環境也就省去一些沒必要要的環節。node

若是你有好的建議和想法能夠在評論區留言,或者郵箱聯繫: shanyanwt@163.com
願你保持獨立思考、不卑、不亢、不慫努力長成本身喜歡的樣子

我是一隻孤獨的狼......歡迎star

相關文章
相關標籤/搜索