iTwin / itwinjs-core

Monorepo for iTwin.js Library
https://www.itwinjs.org
MIT License
623 stars 211 forks source link

Issue with webpack bundling with @bentley/imodeljs-native #108

Closed PKASHYAP-BEC closed 4 years ago

PKASHYAP-BEC commented 4 years ago

I am getting runtime error for @bentley/imodeljs-win32-x64 after webpack bundling, please suggest the way so that I can generate a Production build. here is my webpack config below image

wgoehrig commented 4 years ago

As far as I know, the iModel.js native addon loader has not been tested with the native-ext-loader. The iModel.js native addon is loaded dynamically, and I wouldn't expect a webpack loader to really be able to follow that import.

Our usual guidance for webpacking iModel.js backends is that, at a minimum, you need to mark the "@bentley/imodeljs-native" package as a webpack external, since it cannot be included in a JS bundle. You should be able to do that by adding the following to your webpack config:

module.exports = {
    // ...
    externals: {
        "@bentley/imodeljs-native": "commonjs @bentley/imodeljs-native",
    }    
}

You'll also want to copy the @bentley/imodeljs-native package to a node_modules dir in your {output.path} (in your casedist/server/node_modules) - assuming that's the directory you actually deploy. You can do that either as a separate post-build step or using CopyWebpackPlugin.

There are actually a number of common webpack configurations we recommend as best practices for iModel.js backends, including:

To easily include all this behaviour, you can use our BackendDefaultsPlugin in your webpack config. An example of that (based on the config you included), would look something like:

const { BackendDefaultsPlugin } = require("@bentley/webpack-tools-core");
// ...

module.exports = {
    ...baseConfig,
    entry: './src/server/index.ts',
    output: {
        filename: 'index.js',
        path: path.resolve(__dirname, path.join('dist', 'server')),
    },
    node: {
        __dirname: false,
    },

    resolve: {
        // Add `.ts` and `.tsx` as a resolvable extension.
        extensions: ['.ts', '.tsx', '.js']
    },
    module: {
        rules: [

            // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            { test: /\.(ts|tsx)?$/, loader: 'ts-loader' },
        ]
    },
    plugins: [
        new BackendDefaultsPlugin(),
        new Dotenv(),
        new CleanWebpackPlugin(),
        new CopyPlugin({
            patterns: [{
                from: 'src/server/assets',
                to: 'assets',
            }],
        }),
    ],
}
PKASHYAP-BEC commented 4 years ago

Thank you team , We are able to resolve the issue , so closing this issue here.

thanks.