sanity-io / image-url

Tools to generate image urls from Sanity content
https://www.sanity.io/docs/presenting-images#mY9Be3Ph
MIT License
67 stars 23 forks source link

Issue when webpacking for angular universal #12

Open ayyash opened 4 years ago

ayyash commented 4 years ago

When I use @sanity/image-url in my client project, it works fine

import imageUrlBuilder from '@sanity/image-url';
 constructor() {
            this.builder = imageUrlBuilder({
            projectId: ConfigService.Config.Sanity.ProjectId,
            dataset: ConfigService.Config.Sanity.Dataset
        }); 
    }

and the library used is lib/browser/image-url.umd.js. Then I build for angular ssr, and I use the following webpack config:


module.exports = {
    mode: 'none',
    entry: { server: './server.ts' },
    resolve: { extensions: ['.js', '.ts'], mainFields: [ 'main', 'module'] },
    target: 'node',
    // this makes sure we include node_modules and other 3rd party libraries
    externals: [/(node_modules|main\..*\.js)/],
    output: {
        path: path.join(__dirname, '../garage.host/functions'),
        filename: '[name].js'
    },
    module: {
        rules: [{ test: /\.ts$/, loader: 'ts-loader' }]
    },
    plugins: [
        // Temporary Fix for issue: https://github.com/angular/angular/issues/11580
        // for "WARNING Critical dependency: the request of a dependency is an expression"
        new webpack.ContextReplacementPlugin(
            /(.+)?angular(\\|\/)core(.+)?/,
            path.join(__dirname, 'src'), // location of your src
            {} // a map of your routes
        ),
        new webpack.ContextReplacementPlugin(/(.+)?express(\\|\/)(.+)?/, path.join(__dirname, 'src'), {}),

    ]
};

I use angular-cli to build, now the code used on server render is lib/node/index.js

This errors out with: ERROR TypeError: image_url_1.default is not a function

At this line

 this.builder = image_url_1.default({
            projectId: services_1.ConfigService.Config.Sanity.ProjectId,
            dataset: services_1.ConfigService.Config.Sanity.Dataset
        });

When I remove ".default" it works.

Is this a problem with webpack or some bug? or is it an angular specific issue? can I do something to make the umd bundle instead of the node lib?

Edit more information: the client bundle is created while tsconifg.compilerOptions.module is set to "esnext", the server is created with "commonjs"

bjoerge commented 4 years ago

Hi @ayyash - this is likely an issue with your configuration and maybe related to different module targets for node/browser like you say.

Hard to tell, but perhaps enabling the esModuleInterop option in your tsconfig's compilerOptions would help?