TypeScript Webpack构建不包括node_modules

时间:2018-11-08 15:59:14

标签: typescript webpack aws-lambda

为什么当webpack导入到索引文件中时,buildpack中不包含node_module库?

对于我来说,webpack对我来说仍然是一个妖术,所以我想尝试实现以下内容。

我正在构建一个测试应用程序,以在AWS Lambda Node服务器上作为无服务器代码运行。目标是通过在服务器上具有1个或多个块且没有node_modules文件夹,使部署程序包尽可能小。

我正在用Typescript v3编写,并使用webpack v4为服务器创建捆绑软件。

这是我的目录结构:

  • dist /
  • node_modules /
  • src / index.ts
  • package.json
  • tsconfig.json
  • tslint.json
  • webpack.config.js

这是我的package.json的摘录

  "dependencies": {
    "moment": "^2.22.2"
  },
  "devDependencies": {
    "@types/aws-lambda": "^8.10.15",
    "@types/node": "^10.12.2",
    "awesome-typescript-loader": "^5.2.1",
    "aws-lambda": "^0.1.2",
    "source-map-loader": "^0.2.4",
    "ts-node": "^7.0.1",
    "tslint": "^5.11.0",
    "tslint-loader": "^3.5.4",
    "typescript": "^3.1.6",
    "webpack": "^4.25.1",
    "webpack-bundle-analyzer": "^3.0.3",
    "webpack-cli": "^3.1.2",
    "webpack-node-externals": "^1.7.2"
  }

我要捆绑的index.ts:

import { Handler } from "aws-lambda";
import moment from "moment";

const handler: Handler = async ( event: any ) => {
    const stamp = moment().format( "x" );
    console.log( `process: ${ process.env.NAME } called at ${ stamp }` );
    console.log( event );
    return {
        body: "process completed",
        statusCode: 200
    };
};

export { handler };

我的tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./dist",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "allowJs": true,
        "pretty": false,
        "removeComments": true,
        "esModuleInterop": true,
        "moduleResolution": "node",
        "types": [
            "node"
        ],
        "lib": [
            "es5",
            "es6",
            "dom"
        ]
    },
    "include": [
        "src/**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}

最后是我的webpack.config.js:

const path = require( "path" );
const UglifyJSPlugin = require( "uglifyjs-webpack-plugin" );
const nodeExternals = require( "webpack-node-externals" );

const ROOT = path.resolve( __dirname, "src" );
const DESTINATION = path.resolve( __dirname, "dist" );

module.exports = {
    context: ROOT,
    mode: "production",
    entry: {
        index: "./index.ts"
    },
    target: "node",
    externals: [ nodeExternals() ],
    optimization: {
        minimizer: [
            new UglifyJSPlugin( {
                uglifyOptions: {
                    compress: true,
                    mangle: false,
                    toplevel: false,
                    keep_classnames: true,
                    keep_fnames: true
                }
            } )
        ],
        splitChunks: {
            cacheGroups: {
                node_vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    chunks: "all",
                    priority: 1
                }
            }
        }
    },
    output: {
        filename: "[name].js",
        libraryTarget: "commonjs2",
        path: DESTINATION
    },
    resolve: {
        extensions: [ ".ts", ".js" ],
        modules: [ ROOT, "node_modules" ]
    },
    module: {
        rules: [
            {
                enforce: "pre",
                test: /\.js$/,
                use: "source-map-loader"
            },
            {
                enforce: "pre",
                test: /\.ts$/,
                exclude: /node_modules/,
                use: "tslint-loader"
            },
            {
                test: /\.ts$/,
                exclude: [ /node_modules/ ],
                use: "awesome-typescript-loader"
            }
        ]
    },
    devtool: "cheap-module-source-map",
    devServer: {}
};

运行webpack时,我得到以下控制台输出:

Version: webpack 4.25.1
Time: 4856ms
Built at: 2018-11-08 15:41:09
   Asset      Size  Chunks             Chunk Names
index.js  3.83 KiB       0  [emitted]  index
Entrypoint index = index.js
[0] ./index.ts 3.11 KiB {0} [built]
[1] external "moment" 42 bytes {0} [built]

将其部署到AWS Lambda并调用函数时,出现以下错误:

{
    "errorMessage": "Cannot find module 'moment'",
    "errorType": "Error",
    "stackTrace": [
    "Function.Module._load (module.js:474:25)",
    "Module.require (module.js:596:17)",
    "require (internal/module.js:11:18)",
    "Object.<anonymous> (/var/task/index.js:1:3963)",
    "__webpack_require__ (/var/task/index.js:1:323)",
    "Object.<anonymous> (/var/task/index.js:1:3595)",
    "__webpack_require__ (/var/task/index.js:1:323)",
    "module.exports.__awaiter.__awaiter.P (/var/task/index.js:1:1650)",
    "Object.<anonymous> (/var/task/index.js:1:1695)"
    ]
}

1 个答案:

答案 0 :(得分:4)

由于使用了nodeExternals,因此将每个依赖项都声明为外部依赖项(即:执行时必须存在node_modules)。