阅读 452

webpack打包,生成js,提供给node和浏览器使用

目标

1. 打包后,node和浏览器能够使用.
2. 可以作为SDK提供给node,或者是前端
3. 打包后,可以发布npm包
复制代码

项目搭建

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>
复制代码

npm包发布

1. 修改package.json,修改main中,"./dist/webpack-numbers.js"
{
  "name": "test-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "./dist/webpack-numbers.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"
  }
}
2. npm adduser, 写入 user password emial
3. npm pubilsh,从而可以实现发布,可以npm网站查看自己的包
复制代码
关注下面的标签,发现更多相似文章
评论