1、目标:

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

2、项目搭建:

2.1)项目初始化:

1. mkdir webpack-build
2. cd webpack-build
3. npm init,不停回车,然后最后输入yes即可

2.2)项目结构:

|
| - package.json
| - webpack.config.js
| - node_modules
| - index.js
| - dist

2.3)webpack.config.js:(webpack配置)

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"
}
};

此处需要进行设置,libraryTarget: "umd" globalObject: "this"这样就能够使用在node和浏览器中。

2.4)index.js:(webpack入口文件)

export function numToWord(num) {
return console.log('object')
}

2.5)package.json:(npm文件,项目依赖项及项目基础信息)

{
"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"
}
}

2.6)webpack打包:

npm run build

执行完成后,会在./dist目录下生成webpack-numbers.js文件(webpack.conf.js中filename属性指定)

注:这里可能会遇到一个错误:TypeError: Cannot read property 'properties' of undefined,解决方法:

This was broken by a webpack update, see webpack/webpack#8082

A workaround for now is to update both, webpack and webpack-cli in package.json:

"webpack": "^4.20.2",
"webpack-cli": "^3.1.1",

​https://github.com/plotly/dash-component-boilerplate/issues/12​

3、测试:

3.1)html中测试:

进入dist目录,编写test.html,如下:

<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>

3.2)node中测试:

进入dist目录,编写test.js,如下:

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

node test.js执行。

4、npm发布:

修改package.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"
}
}

修改main属性。然后执行:

npm adduser, 写入 user password emial
npm pubilsh,从而可以实现发布,可以npm网站查看自己的包