지돌이의 블로그 입니다!

openpgp을 사용하는 프로젝트를 webpack으로 번들링하면 아래와 같은 오류가 발생한다.

Error: Cannot find module 'stream'
    at o (/bundle.js:4293:292)
    at /bundle.js:4293:449
    at Object.<anonymous> (/bundle.js:28885:38)
    at Object.76.stream (/bundle.js:28943:4)
    at o (/bundle.js:4293:398)
    at /bundle.js:4293:449
    at Object.<anonymous> (/bundle.js:28422:13)
    at Object.75../node-conversions (/bundle.js:28875:4)
    at o (/bundle.js:4293:398)
    at /bundle.js:4293:449

이런 경우 Webpack에서 openpgp패키지의 dist대신 src를 쓰게 하고

const webpack = require('webpack');
const path = require('path');

module.exports = {
    target: 'node',
    mode: 'production',
    entry: {
        main: './src/index.ts'
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        libraryTarget: 'commonjs2'
    },
    devtool: 'source-map',
    resolve: {
        extensions: ['.ts', '.tsx', '.js'],
        alias: {
            '@src': path.resolve(__dirname, 'src')
        }
    },
    externals: {
        'crypto': 'commonjs crypto',
        'fs': 'commonjs fs',
        'stream': 'commonjs stream'
    },
    module: {
        rules: [
            // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            { test: /\.tsx?$/, loader: "ts-loader" },

            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules\/(?!(openpgp)\/).*/,
                include: [
                    path.resolve(__dirname, "src"),
                    path.resolve(__dirname, "node_modules/openpgp")
                ],
                options: {
                    plugins: ['dynamic-import-webpack']
                }
            },
        ]
    },
    resolve: {
        modules: ['node_modules', 'src'],
        extensions: ['.js', '.json', '.jsx', '.ts'],
        alias: {
            openpgp: 'openpgp/src/index.js',
            'tweetnacl/nacl-fast-light.js': 'tweetnacl/nacl-fast.js'
        }
    },
    plugins: [
        new webpack.ContextReplacementPlugin(
            /openpgp/,
            '',
            {
                crypto: 'crypto',
                stream: 'stream',
                buffer: 'buffer',
                zlib: 'zlib',
                util: 'util'
            }
        )
    ],
    optimization: {
        minimize: false
    }
};

 

필요한 dependency들을 추가해주면 된다.

package.json의 dependencies에

    "asmcrypto.js": "github:openpgpjs/asmcrypto#6e4e407b9b8ae317925a9e677cc7b4de3e447e83",
    "elliptic": "github:openpgpjs/elliptic#6b7801573b8940a49e7b8253176ece2725841efd",
    "email-addresses": "github:openpgpjs/email-addresses#686743c6452b44bafcd06d47db7f36ddf3f3f118",

추가한다.

(주의할점은 그냥 npm install 으로 설치하면 안되고 openpgpjs의 github 리포지터리에서 가져와야 한다. 기존의 패키지를 openpgp에서 수정해서 쓰는것이기 때문)

그리고

$ npm update

$ npm install --save web-stream-tools tweetnacl text-encoding-utf-8 @mattiasbuelens/web-streams-polyfill

Comment +0