环境
win10 + webstrom 2019 + webpack4.x + yarn
tree shaking 作用
生产环境自动启用
开发模式需要配置(过滤不适用的模块),打包后的 js 会有一些注释如:
/*! exports provided: add,sub,mul */ /*! exports used: add,mul */
文件结构
. ├── build //配置文件 │ ├── build.js │ ├── bundle.js │ ├── common.js │ └── dev.js ├── dist //打包后生成的目录 │ ├── 6efdf170-app.js │ └── index.html ├── package.json ├── src │ ├── js │ │ ├── app.js │ │ └── math.js │ └── template │ └── index.html └── yarn.lock
package.json
{ "name": "sample","version": "1.0.0","private": true,"license": "MIT","sideEffects": [ "*.css" ],"scripts": { "bundle": "webpack --config ./build/bundle.js","build": "webpack --config ./build/build.js","dev": "webpack-dev-server --config ./build/dev.js" },"devDependencies": { "clean-webpack-plugin": "^3.0.0","html-webpack-plugin": "^3.2.0","webpack": "^4.33.0","webpack-cli": "^3.3.3","webpack-dev-server": "^3.7.1","webpack-merge": "^4.2.1" } }
/src/js 中代码
app.js
import {add,mul} from ‘./math.js‘; console.log("add(11 + 11): ",add(11,11)); console.log("mul(11 + 11): ",mul(11,11)); window.document.body.innerHTML = ‘<h1>hello world</h1>‘;
math.js
export const add = function (a,b) { return a + b; },sub = function (a,b) { return a - b; },mul = function (a,b) { return a * b; };
/src/template/index.html 模版文件
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"></div> </body> </html>
/build/下的打包配置文件
build.js
const common = require(‘./common.js‘); const merge = require(‘webpack-merge‘); module.exports = merge(common,{ mode: ‘production‘,devtool: ‘cheap-module-source-map‘ });
bundle.js
const common = require(‘./common.js‘); const merge = require(‘webpack-merge‘); module.exports = merge(common,{ mode: ‘development‘,devtool : ‘cheap-module-eval-source-map‘,optimization: { usedExports: true } });
common.js
const HtmlWebpackPlugin = require(‘html-webpack-plugin‘); const {CleanWebpackPlugin} = require(‘clean-webpack-plugin‘); module.exports = { entry: { app: ‘./src/js/app.js‘ },output: { filename: ‘[hash:8]-[name].js‘ },plugins: [ new HtmlWebpackPlugin({ template: ‘./src/template/index.html‘ }),new CleanWebpackPlugin() ] };
dev.js
const common = require(‘./common.js‘); const bundle = require(‘./bundle.js‘); const merge = require(‘webpack-merge‘); const path = require(‘path‘); module.exports = merge(common,bundle,{ devServer: { contentBase: path.resolve(‘../dist‘),host: "127.0.0.1",port: 12858,hot: true,hotOnly: true,} });
打包命令(package.json 中 script 中配置的)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。