我是angularjs的新手,在我的项目中我有很多依赖项js文件,这影响了我对每个文件的项目性能有单独的请求,因此有这么多文件我最终得到了很多请求。我希望使用webpack创建这些文件的单个捆绑包...我正在寻找使用webpack创建单个文件的步骤吗?
答案 0 :(得分:4)
If you are new to webpack please go through this webpack video tutorial.
Assuming you are using Angular 2/4/5 you can follow the below steps.
Step 1 :- install webpack by using node command.
npm install -g webpack
Step 2 :- Create "webpack.config.js" and define how you want to bundle. This file is a webpack configuration file which defines the road map of your bundling. For example in the below config i am creating three bundles. "Startup" , "SupplierModule" and "CustomerModule". These bundles will be compiled to the "dist" directory. In case you are new to webpack go through this webpack article
var path = require('path');
module.exports = {
entry: {
CustomerModule: "./Modules/CustomerModule.js",
SupplierModule: "./Modules/SupplierModule.js",
Startup: [ "./node_modules/core-js/client/shim.min.js",
"./node_modules/zone.js/dist/zone.js",
"./node_modules/reflect-metadata/Reflect.js",
"./Startup.js"
]
},
output: {
path: path.join(__dirname, "dist"),
publicPath: "/dist/",
filename: "[name].bundle.js"
}
};
Step 3 :- Go the folder where you have made this file and execute webpack if you want to compress the file you can use "-p" option.
webpack -p
If everything goes well you should see something as shown below. You can see he has created three bundles as per the road map of the "webpack" config file defined in the previous step.
Step 4 :- In your angular index page , remove all JS files and add reference to the files from dist folder. Please note the main angular page only need the reference to startup.js and other modules will be loaded on demand.
In case you are using lazy loading using systemJS then the below three steps are also needed.
Step 1: – Get “es6-promise-loader” and replace Systemjs
Replace systemjs with es6 promise loader. So do a NPM and get it.
Step 2 :- Install node types
npm install -save @types/node
Step 3 :- your dynamic module loader code will also change now. So the routing code becomes something as shown below
export const MainRoutes = [
{ path: 'Customer', loadChildren: () => require('es6-promise-
loader!../Modules/CustomerModule')('CustomerModule')},
{ path: 'Supplier', loadChildren: () => require('es6-promise-
loader!../Modules/SupplierModule')('SupplierModule') },
{ path: '', component: HomeComponent },
{ path: 'Shell.html', component: HomeComponent },
{ path: 'Help', component: HelpComponent, outlet: "helpoutlet" }
];
Do webpack again to bundle the files.If you see the bundling output you can see 0.bundle.js , 1.bundlejs which is sign that your lazy loading bundling is working well.
Happy bundling...