windows10 下使用webpack建立library

參考:javascript

https://github.com/kalcifer/webpack-library-example
https://webpack.js.org/guides/author-libraries

說明:html

最近結合webpack官方文檔和示例代碼在windows10下使用webpack建立library時碰見一些問題,在此總結一下

建立library:java

  • 基礎知識準備node

    1. 庫使用方法
           ES2015 module import:
               import * as webpackNumbers from 'webpack-numbers';
               // ...
               webpackNumbers.wordToNum('Two');
    
           CommonJS module require:
               const webpackNumbers = require('webpack-numbers');
               // ...
               webpackNumbers.wordToNum('Two');
    
           AMD module require:
               require(['webpackNumbers'], function (webpackNumbers) {
                 // ...
                 webpackNumbers.wordToNum('Two');
               });
               
           via a <script>:
               <!doctype html>
               <html>
                 ...
                 <script src="https://unpkg.com/webpack-numbers"></script>
                 <script>
                   // ...
                   // Global variable
                   webpackNumbers.wordToNum('Five')
                   // Property in the window object
                   window.webpackNumbers.wordToNum('Five')
                   // ...
                 </script>
               </html>
       2. 暴露 library
           why:爲了讓你的 library 可以在各類用戶環境(consumption)中可用
           how:
               在output中添加 library屬性
                   當你在 import 引入模塊時,這能夠將你的 library bundle 暴露爲全局變量
                   
               在output中添加 libraryTarget 屬性 
                   1) 控制 library 以不一樣方式暴露,讓 library 和其餘環境兼容
               
                   2) 能夠經過如下方式暴露 library:
                       變量:做爲一個全局變量,經過 script 標籤來訪問(libraryTarget:'var')
                       this:經過 this 對象訪問(libraryTarget:'this')
                       window:經過 window 對象訪問,在瀏覽器中(libraryTarget:'window')
                       UMD:在 AMD 或 CommonJS 的 require 以後可訪問(libraryTarget:'umd')
                       
                   3) 若是設置了 library 但沒設置 libraryTarget,則 libraryTarget 默認爲 var。
                   
               output.globalObject
                   string: 'window'
                   要使umd 在瀏覽器和node.js 上均可用,globalObject須要設置成this
                   
               示例:
                   output: {
                       ...
                        library: 'webpackNumbers',
                        libraryTarget: 'umd',
                        globalObject: 'this'
                   }

步驟:webpack

  • 建立目錄並安裝相關工具git

    1. $ mkdir webpack-numbers-library //建立webpack-numbers-library
       2. $ cd webpack-numbers-library//進入webpack-numbers-library目錄
       3. $ npm init -y //初始化 npm
       4. $ npm install webpack --save-dev //在本地安裝 webpack
       5. $ npm install webpack-cli --save-dev // 安裝 webpack-cli
       6. $ npm install lodash --save-dev //安裝 lodash
  • 添加文件github

    1. 添加 src/
           index.js
               import _ from 'lodash';
               import numRef from './ref.json';
               
               export function numToWord(num) {
                   return _.reduce(numRef, (accum, ref) => {
                       return ref.num === num ? ref.word : accum;
                   }, '');
               };
               
               export function wordToNum(word) {
                   return _.reduce(numRef, (accum, ref) => {
                       return ref.word === word && word.toLowerCase() ? ref.num : accum;
                   }, -1);
               };
               
           ref.json
               [
                   {
                       "num": 1,
                       "word": "One"
                   },
                   {
                       "num": 2,
                       "word": "Two"
                   },
                   {
                       "num": 3,
                       "word": "Three"
                   },
                   {
                       "num": 4,
                       "word": "Four"
                   },
                   {
                       "num": 5,
                       "word": "Five"
                   },
                   {
                       "num": 0,
                       "word": "Zero"
                   }
               ]
       2. 添加examples/
       
           browser/index.html
               <html>
               <head>
                   <title>webpack numbers library</title>
                   <script type='text/javascript' src='https://unpkg.com/lodash@4.16.6'></script>
               </head>
               <body>
                   <div id='root'></div>
                   <!--經過<script> 加載庫-->
                   <script type='text/javascript' src='./webpack-numbers.js'></script>
                   <script type='text/javascript'>
                       document.getElementById('root').innerHTML = " This is a browser example where and api is called to transalate 'One' to '1' \n Results: wordtonum('One') === " + window.webpackNumbers.wordToNum('Five');
                   </script>
               </body>
               </html>
               
           node/example.js
               require('lodash');
               var webpackNumbers = require('./webpack-numbers.js');//CommonJS module require
               var out = function () {
                   process.stdout.write('This is the result for numToWord(1) === ' + webpackNumbers.numToWord(1));
               };
               out();
    
       3. 添加webpack.config.js    
           const path = require('path');
           
           module.exports = {
               mode: 'production',//啓用 uglifyjs 壓縮插件進行壓縮輸出
               entry: './src/index.js',
               output: {
                   path: path.resolve(__dirname, './dist'),
                   filename: 'webpack-numbers.js',
                   library: 'webpackNumbers',//暴露 library爲webpackNumbers的全局變量
                   libraryTarget: 'umd',//讓 library 和其餘環境兼容:umd:在 AMD 或 CommonJS 的 require 以後可訪問
                   globalObject: 'this',//使umd 在瀏覽器和node.js 上均可用,globalObject須要設置成this
               },
               externals: {//外部化 lodash:放棄對外部 library 的控制,而是將控制權讓給使用 library 的用戶
                   lodash: {
                       commonjs: 'lodash',
                       commonjs2: 'lodash',
                       amd: 'lodash',
                       root: '_'
                   }
               },
               module: {
                   rules: [
                       {
                           test: /\.(js)$/,
                           exclude: /(node_modules|bower_components)/,
                           use: 'babel-loader'
                       }
                   ]
               }
           };
    
       4. 最終的文件結構以下:
           │  package-lock.json
           │  package.json
           │  webpack.config.js
           │
           ├─examples
           │  ├─browser
           │  │      index.html
           │  │
           │  └─node
           │          example.js
           ├─node_modules
           │
           └─src
                   index.js
                   ref.json
  • 安裝babel-loaderweb

    $ npm install babel-loader --save-dev
       最新的 babel-loader版本是8.x, 直接安裝, 後面執行npm build xxx的時候會報如下錯誤
           ERROR in ./src/index.js
           Module build failed (from ./node_modules/babel-loader/lib/index.js):
           Error: Cannot find module '@babel/core'
            babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.
       
       根據錯誤信息的提示, 咱們安裝babel-loader 7.x版本babel-core
       $ npm install babel-core babel-loader@7 --save-dev
           babel-loader@7.1.5
           babel-core@6.26.3
  • 修改package.jsonnpm

    從webpack-library-example 示例中package.json 拷貝如下code 到
       {
           ...
             "main": "dist/webpack-numbers.js",//添加生成 bundle 的文件路徑
             "scripts": {
               "build:browser": "webpack && cp dist/webpack-numbers.js examples/browser",
               "build:node": "webpack && cp dist/webpack-numbers.js examples/node/ && node examples/node/example.js",
               "test": "echo \"Error: no test specified\" && exit 1"
             }
           ...      
       }
  • 測試browserjson

    1. $ npm run build:browser
       2. 在瀏覽器中打開index.html
          頁面顯示:
          This is a browser example where and api is called to transalate 'One' to '1' Results: wordtonum('One') === 5
  • 測試 node

    1. $ npm run build:node
       2. 打印如下信息:
           This is the result for numToWord(1) === One
相關文章
相關標籤/搜索