我是webpack的新手,我发现在生产环境中我们可以减少整体代码的大小。目前,webpack构建大约8MB的文件,而main.js构建大约5MB的文件。如何减少生产构建中的代码大小?我从互联网上找到了一个样本webpack配置文件,并为我的应用程序进行了配置,然后运行npm run build
并开始构建它,并在./dist/
目录中生成了一些文件。
- 这些文件仍然很重(与开发版本相同)
- 如何使用这些文件?目前,我正在使用webpack-dev-server运行该应用程序。
package.json文件
{
"name": "MyAPP",
"version": "0.1.0",
"description": "",
"main": "src/server/server.js",
"repository": {
"type": "git",
"url": ""
},
"keywords": [
],
"author": "Iam",
"license": "MIT",
"homepage": "http://example.com",
"scripts": {
"test": "",
"start": "babel-node src/server/bin/server",
"build": "rimraf dist && NODE_ENV=production webpack --config ./webpack.production.config.js --progress --profile --colors"
},
"dependencies": {
"scripts" : "", ...
},
"devDependencies": {
"scripts" : "", ...
}
}
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var public_dir = "src/frontend";
var ModernizrWebpackPlugin = require('modernizr-webpack-plugin');
module.exports = {
devtool: 'eval-source-map',
entry: [
'webpack-hot-middleware/client?reload=true',
path.join(__dirname, public_dir , 'main.js')
],
output: {
path: path.join(__dirname, '/dist/'),
filename: '[name].js',
publicPath: '/'
},
plugins: [
plugins
],
module: {
loaders: [loaders]
}
};
webpack.production.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var public_dir = "src/frontend";
var ModernizrWebpackPlugin = require('modernizr-webpack-plugin');
console.log(path.join(__dirname, 'src/frontend' , 'index.html'));
module.exports = {
devtool: 'eval-source-map',
entry: [
'webpack-hot-middleware/client?reload=true',
path.join(__dirname, 'src/frontend' , 'main.js')
],
output: {
path: path.join(__dirname, '/dist/'),
filename: '[name].js',
publicPath: '/'
},
plugins: [plugins],
resolve: {
root: [path.resolve('./src/frontend/utils'), path.resolve('./src/frontend')],
extensions: ['', '.js', '.css']
},
module: {
loaders: [loaders]
}
};
自己学习。我将回答第二个问题:
除了使用webpack-dev-server外,您还可以运行“ express”。使用npm install“ express”并在项目的根目录中创建server.js,如下所示:
然后,在package.json中,添加一个脚本:
最后,运行应用程序:
npm run start
启动服务器可以在以下位置查看详细示例:https : //alejandronapoles.com/2016/03/12/the-simplest-webpack-and-express-setup/ (示例代码与最新软件包不兼容,但可以使用进行细微调整)