简体   繁体   中英

Node module cross build targets for deployment in npm

I have my ES6 module that I want to build to target different environments. I don't know how to do this or if I should use webpack or rollup.

Build targets

  1. ES6 environments like Vue.
  2. Commonjs like node backend or some webpack builds.
  3. The browser, the script tag.

Project directory structure


src

--Dog.js

index.js

package.json


Project Files

Dog.js

class Dog{
  //Typical Dog stuff
}
export default Dog;

index.js

import Dog from "./src/Dog";
export {
  Dog
}

webpack.config.js

module.exports = {
  target: 'node',
  mode: 'production',
};

package.json (relevant parts)

"files": [
  "dist",
  "src"
]

Is there any way to automatize this process or should I just write a new library for each target manually? And if there is how the projects that import my module know which build is right for their environment?

Just use different webpack configs for different environments and targets. It is a common approach.

This is what i think it works with a minimal webpack configuration. The dist folder and its contents are created by webpack.

Project directory structure


src

--Dog.js

dist

--dog.common.js

--dog.lib.min.js

index.js

package.json

webpack.config.js


webpack.config.js

const path = require("path");

var commonJsConfig = {
  target: 'node',
  mode: 'production',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'dog.common.js',
    libraryTarget: 'commonjs'
  }
};

var browserConfig = {
  target: 'web',
  mode: 'production',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'dog.lib.min.js'
  }
};

module.exports = [commonJsConfig, browserConfig];

package.json (relevant parts)

  • main tells backend and webpack legacy projects to use the commonjs format.
  • module is for es6 format
  • unpkg for the browser
  • files tell npm wich files to upload
"main": "dist/dog.common.js",
"module": "index.js",
"unpkg": "dist/dog.lib.min.js",
"files": [
  "dist",
  "src"
],
"scripts": {
  "build": "webpack"
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM