rollup - importing external library

Viewed 1940

Earlier I used the script to use the library:

Now I use yarn and rollup to build project with next files. package.json:

{
  "name": "maplib",
  "version": "1.0.0",
  "main": "src/main.js",
  "license": "MIT",
  "devDependencies": {
  "@babel/cli": "^7.10.5",
  "@babel/core": "^7.10.5",
  "@babel/node": "^7.10.5",
  "@babel/preset-env": "^7.10.4",
  "@rollup/plugin-node-resolve": "^8.4.0",
  "rollup": "^2.22.2"
  },
  "dependencies": {
    "mapbox-gl": "^1.11.1"
  },
  "scripts": {
    "build": "rollup -c"
  }
}

rollup.config.js:

import resolve from '@rollup/plugin-node-resolve';
                         
export default {
  input: 'src/main.js',
  external: ['mapbox-gl-dev'],
  output: {
    file: 'src/blazorMap/dist/MapBoxBlazor.js',
    format: 'iife',
    globals: {
      mapboxgl: 'mapboxgl'
    },
    plugins: [
      resolve(), // so Rollup can find `mapbox-gl`
    ]
  }
};

and main.js:

import * as mapboxgl from 'mapbox-gl'

export function init(o) {
    
    this.assign(mapboxgl, "accessToken", o.accessToken);
        this.mapblazor = new mapboxgl.Map(
        container   = o.container,
        style       = o.mapStyle,
        center      = o.mapCenter,
        zoom        = o.mapZoom
    );
}

I get error message: https://rollupjs.org/guide/en/... dependency mapbox-gl (imported by src\main.js) (!) Missing global variable name Use output.globals to specify browser global variable names corresponding to external modules mapbox-gl (guessing 'mapboxgl') created src/blazorMap/dist/MapBoxBlazor.js in 37ms How I can fix issue with importin mapbox-gl?

1 Answers

You may need '@rollup/plugin-commonjs', move the position of 'plugins' outside of output, and set a 'name' property to 'output':

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs'

export default {
  input: 'src/main.js',
  external: ['mapbox-gl-dev'],
  output: {
    file: 'src/blazorMap/dist/MapBoxBlazor.js',
    format: 'iife',
    globals: {
      mapboxgl: 'mapboxgl',
    },
    name: 'xxx'
  },
  plugins: [
    resolve(), // so Rollup can find `mapbox-gl`
    commonjs(),
  ],
};
Related