I'm tinkering with the tree shaking example from the webpack document. But it seems that tree shaking doesn't work once I add babel-loader to the mix.
Here is an overview of my project:
index.js:
import { cube } from "./math";
function component() {
const element = document.createElement('pre');
element.innerHTML = [
'Hello webpack!',
'5 cubed is equal to ' + cube(5)
].join('\n\n');
return element;
}
document.body.appendChild(component());
math.js:
export function square(x) {
console.log('square');
return x * x;
}
export function cube(x) {
console.log('cube');
return x * x * x;
}
.babelrc:
{
"presets": [
["env", { "modules": false }],
"react"
],
"plugins": ["react-hot-loader/babel"]
}
package.json:
{
"dependencies": {
"react": "^16.3.1",
"react-dom": "^16.3.1",
"react-hot-loader": "^4.0.1"
},
"name": "react-webpack-starter",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack -p --optimize-minimize"
},
"sideEffects": false,
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14",
"webpack-dev-server": "^3.1.3"
}
}
webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'index_bundle.js'
},
mode: 'production',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
};
Поскольку index.js не использует квадратную функцию, квадратную функцию следует удалить из пакета. Однако, когда я открываю bundle.js и ищу «квадрат», я все еще могу найти функцию квадрата и оператор журнала консоли. После того, как я закомментирую спецификацию babel-loader в конфигурации webpack и снова выполните сборку npm run build, в сгенерированном файле пакета больше не будет слова "квадрат".
Я указал modules: false < / strong> в .babelrc.
Кто-нибудь может сказать мне, что может вызвать эту проблему?
Вот репо для воспроизведения: https://github.com/blogrocks/treeshaking-issue.git