webpack打包,生成js,提供給node和瀏覽器使用

Neu-Li發表於2019-04-10

webpack打包

目標

1. 打包後,node和瀏覽器能夠使用.
2. 可以作為SDK提供給node,或者是前端
複製程式碼

專案搭建

1: 專案初始化

1. mkdir webpack-build
2. cd webpack-build
3. npm init,不停回車,然後最後輸入yes即可
複製程式碼

2: 檔案列表

|
| - package.json
| - webpack.config.js
| - node_modules
| - index.js
| - dist
複製程式碼

3: webpack配置

webpack.config.js配置如下:

const path = require("path");
module.exports = {
  mode: "production",
  entry: "./index.js",
  output: {
    path: path.resolve(__dirname, "./dist"),
    filename: "webpack-numbers.js",
    libraryTarget: "umd",
    globalObject: "this",
    library: "webpackNumbers"
  }
};

複製程式碼

此處需要進行設定,這樣就能夠使用在node和瀏覽器中

libraryTarget: "umd" globalObject: "this"

4: index.js編寫

export function numToWord(num) {
  return console.log('object')
}
複製程式碼

package.json編寫

{
  "name": "test-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-preset-env": "^1.6.1",
    "eslint": "^3.9.1",
    "eslint-loader": "^1.6.1",
    "lodash": "^4.16.6",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.1"
  }
}
執行:npm run build,會在dist目錄下生成webpack-numbers.js檔案
複製程式碼

使用webpack-numbers.js檔案

1. cd dist
2. touch test.js
複製程式碼

編寫test.js檔案:

let app = require("./webpack-numbers.js");
let data = app.numToWord();
console.log(data);

複製程式碼
1. node中使用,應用打包後的webpack-numbers.js,node test.js
2. 瀏覽器中使用
    <html>
      <head>
        <title>webpack library example - Transalating numbers</title>
        <script
          type="text/javascript"
          src="https://unpkg.com/lodash@4.16.6"
        ></script>
      </head>
      <body>
        <div id="root"></div>
        <script type="text/javascript" src="./webpack-numbers.js"></script>
        <script type="text/javascript">
          console.log(webpackNumbers.wordtonum("One"));
        </script>
      </body>
    </html>
複製程式碼

相關文章