GithubHelp home page GithubHelp logo

krasimir / webpack-library-starter Goto Github PK

View Code? Open in Web Editor NEW
1.4K 34.0 293.0 605 KB

Webpack based boilerplate for producing libraries (Input: ES6, Output: universal library)

License: MIT License

JavaScript 61.80% HTML 32.68% TypeScript 5.51%

webpack-library-starter's Introduction

Webpack library starter

Webpack based boilerplate for producing libraries (Input: ES6/TypeScript, Output: universal library)

Features

  • Webpack 5 based.
  • ES6 or TypeScript as a source.
  • Exports in a umd format so your library works everywhere.
  • Test setup with Jest.

Process

ES6/TypeScript source files
       |
       |
    webpack
       |
       +--- babel
       |
  ready to use
     library
  in umd format

Have in mind that you have to build your library before publishing. The files under the lib folder are the ones that should be distributed.

Getting started

  1. Setting up the name of your library
  • Open webpack.config.js file and change the value of libraryName variable.
  • Open package.json file and change the value of main property so it matches the name of your library.
  1. Build your library
  • Run yarn install (recommended) or npm install to get the project's dependencies
  • Run yarn build to produce minified version of your library.
  1. Development mode
  • Run yarn dev. This command will generate a non-minified version of your library and will run a watcher so you get the compilation on file change.
  1. Running the tests
  • Run yarn test

Scripts

  • yarn build - produces production version of your library under the lib folder
  • yarn build-amd - produces an AMD version that works with RequireJS
  • yarn dev - produces development version of your library and runs a watcher
  • yarn dev-amd - produces an AMD development version of your library and runs a watcher
  • yarn test - well ... it runs the tests :)
  • yarn test-watch - same as above but in a watch mode

Readings

Misc

An example of using dependencies that shouldn’t be resolved by webpack, but should become dependencies of the resulting bundle

In the following example we are excluding React and Lodash:

{
  devtool: 'source-map',
  output: {
    path: '...',
    libraryTarget: 'umd',
    library: '...'
  },
  entry: '...',
  ...
  externals: {
    react: 'react'
    // Use more complicated mapping for lodash.
    // We need to access it differently depending
    // on the environment.
    lodash: {
      commonjs: 'lodash',
      commonjs2: 'lodash',
      amd: '_',
      root: '_'
    }
  }
}

webpack-library-starter's People

Contributors

alvisisme avatar brodanoel avatar ergenekonyigit avatar folkengine avatar ghstahl avatar jisupark avatar jonarod avatar krasimir avatar lesansley avatar mikeerickson avatar mkurapov avatar qu4tro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webpack-library-starter's Issues

npm test does not exit gracefully

Steps to reproduce the issue:

  1. Clone the repository
  2. npm install
  3. npm build
  4. npm test

Expected:

Tests pass and the process exits gracefully

Actual:

Although the tests pass, you can see that the process does not exit. Looks like it is still running on a 'watch' mode, but I'm unable to find where it is specified (if at all).

It is important that npm test returns after running the tests, so that one could hook up these libraries to CI tools like Travis.

Conceptual doubt if using this project applies to my problem

Hi

I've been struggling with a problem for a while and I've tried to use this project to solve it (although unsuccessfully so far). I'd like to know if what I have in mind is possible before spending much more energy on it...

Context:

I have a project where I use deck.gl to create web maps. It works fine, however, I need the functionality of drawing polygons and for that the deck.gl documentation tells me to use nebula.gl. The sample of the functionality that I need can be found here: https://codesandbox.io/s/deckgl-and-nebulagl-editablegeojsonlayer-no-react-p9yrs?file=/app.js

The problem:

The problem that I have is that on the nebula.gl documentation there's no library compiled to be used on a <script> tag. They only work with the library installed through npm or yarn, then the only way I managed to make it work so far was by compiling the entire project...

My question:

I've read this page: https://krasimirtsonev.com/blog/article/javascript-library-starter-using-webpack-es6 before arriving here on Github. My doubt is: since you're saying on your blog that's possible to compile an individual javascript library, do you think it'd be possible to compile this nebula.gl library in a single file just so I can successfully use it on a <script> tag while serving this file on my own server? Even though I've tried to compile the nebula.gl library I didn't manage to do that, I reached a point that I don't know if what I'm trying to do makes sense since on the nebula.gl documentation I don't find much information about it.

I get Library.js, not library.js

Thanks。

I git clone the project, and npm run build ,npm run dev。

then I get Library.jsLibrary.min.js, not the same as library,js, library.min.js

I dont know why。

In my options, all are Library, or all are library, it should not happen that both Library and library appear

external dependencies

Now, I have a library xx depending jQuery:

import $ from 'jquery'

...

I find #3 , so I write this externals:

externals: {
    'jquery': 'jQuery'
}

It's great! The bundle file is small!

But, when I use my library:

var xx = require('xx')

then use webpack, the library put xx and jQuery together. I don't know how to separate them?

Include a simple demo/docs page?

any chance this can include a simple demo page where you can display the components of your library? Will also help a lot while iterating on the library (gives you a place to test)

transpiling to ES2015? Have a potential solution.

Hi I noticed that if I used async/await or other ES2016 features, then the tests would not recognize the code and fail for various reasons so I assume it wasn't transpiled properly to ES2015.

My solution was to add babel-pollyfill (currently "^6.26.0") as a dependency and adjust the entry point in webpack.config.js to

const config = {
  // ...
  entry: ['babel-polyfill', __dirname + '/src/index.js'],
  // ...
}

``

As a result something like below now works well. Is this a good solution in people's opinion? I got idea from here: babel/babel-loader#249

const wait = async (ms) => (new Promise((resolve) => { setTimeout(resolve, ms) }))

const sdk = async () => {
  await wait(2000);
  return '111111111111'
}
export { Dog, Cat, sdk };

Fonts / Images

Apologies if this is naive, but can this handle font packing as well? Say I'm developing a react library that depends on a UI library such as https://github.com/palantir/blueprint or similar, which has fonts bundled with it.

How can I have webpack build those fonts and include them in my library?

Use Source Maps in Mocha Tests

I tried to naively use this module in my mocha tests: https://github.com/evanw/node-source-map-support

Instead of referencing the line number in my source file, my error stack looks like this:

Error: not implemented
    at MyClass.myFunction (xxx-js/lib/webpack:/xxx-js/node_modules/core-js/modules/es6.reflect.prevent-extensions.js:2:1)
    at Context.<anonymous> (xxx-js/test/MyClass.spec.js:105:12)

about babel plugin.

babel-plugin-add-module-exports is unnecessary in project base on webpack3,i think babel-plugin-transform-runtime need be added.

How to use RequireJS client-side to load the Cat & Dog modules

Hi there

I have successfully loaded and run the bundled file in the following contexts:

  • Directly in the browser via both
    -- a <script> tag
    -- dynamically via JavaScript e.g. document.createElement('script').
  • Using the SystemJS module loader

However, I can't seem to work out how to use an AMD loader to do the same. RequireJS is meant to support AMD but I've been wracking my brains (and the internet) trying to make it work...

Can anyone give any advice on how to consume the out-of-the-box bundle with the Cat and Dog examples via RequireJS, please?

Thanks so much,

Paul

Help with browser

Hi, I try this, and work in test. But can I get this work inside browser.
If I import in html I got error in browser:

`import {Dog} from './lib/webpack-library-starter.min.js';
const dog = new Dog();
Dog.name;

Uncaught SyntaxError: The requested module './lib/webpack-library-starter.min.js' does not provide an export named 'Dog'

Webpack4, babel7

Would it be possible to branch this to update dependencies ? ☺️

Yeoman generator

Good stuff. What about creating a yeoman generator for this starter?

Doesn't support ...spread operator?

Using smething like this within library:

const foo = {};

export default { ...foo };

throws:

Module parse failed: Unexpected token (8:17)
You may need an appropriate loader to handle this file type.
| exports.default = void 0;
| var foo = {};
var _default = { ...foo

Any plans to update this repo to support modern syntax?
Is this repo being maintained? I can post PR

Intellisense doesn’t work after transpiled

Great starter, it really helped me a lot. I just have one problem with it, intellisense work well with my JS file under src, but when i build it, the file generated under lib folder doesn’t. It’s like you’re working with classes that are not exported but they are, since, as I said, they are showing when not transpiled. I was reading about Typescript Declaration Files so my code is well documented and intellisense work properly, but I see a lot of libraries on GitHub without that file. Is something missing for this to properly work or that’s the normal behavior of UMD libraries?

Why use --mode vs ENV

Curious why you should to use a custom option --mode vs using the Node ENV (or NODE_ENV) Surely not a deal breaker by any stretch, more just curious

Having `<script>` tag usage issue

First, thank for this example

In your article, http://krasimirtsonev.com/blog/article/javascript-library-starter-using-webpack-es6

It said

The library should:

  • Be available for in-browser use. Understand including the library via <script> tag.

Thus, I tried this way, and I am having error

<!DOCTYPE html>
<html>
<head>
  <script src="lib/Library.js"></script>
</head>
<body>
  <script>
  var cat = new Cat();
  console.log(cat.name);
  </script>
</body>
</html>

image

Am I missing any? or Is there any another way to make use of <script> tag?

webpack cli error on build

When i run npm run build or npm run dev-amd I receive this message in console log:

[webpack-cli] Invalid value 'true' for the '--amd' option
[webpack-cli] Expected: 'false'

The same happen with "yarn build" command

The build shew me successfully but no amd file is created

Transpile with statics

Does someone was successful with compiling static functions? The following code would break the lib:

class Test {
  static get oneThird() {
    return 3.0 / 1.0;
  }
}

export default Test;

Webpack 4 incompatible

When upgrading to the new Webpack, there is this error:

Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead.

Import https://github.com/websockets/ws

Hi,
I cannot importhttps://github.com/websockets/ws module into library. The webpack throws errors and I dot known how repair it.

Can you help me please?
Thx!

Add example of external dependencies

Figuring out how to include Lodash as a dependency in my library tripped me up quite a bit. I finally found guidance from http://survivejs.com/webpack_react/authoring_libraries/:

{
  devtool: 'source-map',
  output: {
    path: config.paths.dist,
    libraryTarget: 'umd',
    library: config.library
  },
  entry: config.paths.src,
  externals: {
    react: 'react'
    // Use more complicated mapping for lodash.
    // We need to access it differently depending
    // on the environment.
    lodash: {
      commonjs: 'lodash',
      commonjs2: 'lodash',
      amd: '_',
      root: '_'
    }
  },}
}

Build script does not work on Windows

It seems that build script does not work on Windows. The following error occurred:

C:\0temp\webpack-library-starter>npm run build

[email protected] build C:\0temp\webpack-library-starter
WEBPACK_ENV=build webpack

'WEBPACK_ENV' is not recognized as an internal or external command,
operable program or batch file.

npm ERR! Windows_NT 10.0.10240
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Users\Boris\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js" "run" "build"
npm ERR! node v4.2.1
npm ERR! npm v3.3.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] build: WEBPACK_ENV=build webpack
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script 'WEBPACK_ENV=build webpack'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the webpack-library-starter package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! WEBPACK_ENV=build webpack
npm ERR! You can get their info via:
npm ERR! npm owner ls webpack-library-starter
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! C:\0temp\webpack-library-starter\npm-debug.log

Fork request: rollup

Hi,
I tried your starter and I find it amazing, and I also like your article with the full explanation.

This is exactly what I need to make my opensource library testable using ES6 modules, but I really don't like how webpack bundled things, it bloats the final code with a lot of unnecessary lines, whereas Rollup + Babel would only bundle and convert the ES6 code to ES5, then wrap it in the UMD definition.

I think that if you create a rollup-library-starter library it would become very popular. Can you do this? Can we do it together?

Unable to use produced library.js as 3rd party.

Hi,
I cloned the the project and added the following html page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script type="module" src="run.js">
</script>
<body>

</body>
</html>

and run.js:

import {Cat, Dog} from './lib/library.js';

const cat = new Cat();
const dog = new Dog();

And tried running in in Chrome,
But I keep getting Uncaught SyntaxError: The requested module does not provide an export named 'Cat'
I can't figure out why this is....

Travis-CI config

Adding a sample Travis-CI config could be nice for automatic testing.

Here is an easy example.

language: node_js
node_js:
  - "8"
script:
  - yarn test
cache: yarn

I can PR one.

Do you think to add Prettier to the project in the future?

I changed eslint config as prettier default configs, i think this way more clear.

"scripts": {
  "prettier": "prettier --write 'src/**/*.js'",
},
"devDependencies": {
  "eslint-config-prettier": "^2.9.0",
  "eslint-plugin-prettier": "^2.4.0",
  "prettier": "1.9.2",
}

my .eslintrc

"plugins": ["prettier"],

"extends": ["eslint:recommended", "prettier"],

"rules": {
  "prettier/prettier": "error"
}

my .prettierrc

{
  "singleQuote": true
}

Can't get babel-polyfill working with this

I'm trying to get babel-polyfill working with for a library but I'm getting the following error:

TypeError: Cannot read property '_babelPolyfill' of undefined
at Object.<anonymous> (/Users/foo/webpack-library-starter/lib/library.js:73:6)
...

Full replication details:

git clone https://github.com/krasimir/webpack-library-starter.git
cd webpack-library-starter
npm i
npm i --save babel-polyfill

Add import 'babel-polyfill'; to the beginning of "src/index.js".

Add 'babel-polyfill' to "webpack.config.js":

  entry: ['babel-polyfill', __dirname + '/src/index.js'],

Then build and test:

npm run dev
npm run build
npm test

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.