- npm init
- npm install webpack -g
- 根目录下创建index.html并引入dist里生成的的js
- 在入口a.js文件,引入js和 css文件
- 根目录下创建webpack.config.js,注意__dirname是两个下划线
module.exports = { entry: { a:__dirname + '/src/script/a.js', b:__dirname + '/src/script/b.js' }, output: { path: __dirname + '/dist/js', filename: "[name].js" } }
- 运行前,npm install style-loader css-loader --save-dev,且在require中添加style-loader!css-loader!
require('./b.js'); require('style-loader!css-loader!../css/style.css'); function a() { alert('a') } a();
- Terminal控制台输入webpack,自动读取webpack.config.js配置文件,进行打包,dist中会自动生成output输出的js
- 目前根目录下的index.html引入的js是手动添加的a.bundle.js,如果要加入多个生成的js,那么需要用插件html-webpack-plugin,首先是安装npm install html-webpack-plugin --save-dev;然后是在webpack.config.js中加入如下代码
- 同样terminal中输入webpack后,在dist文件中会生成一个默认的index.html文件,文件中引入了dist中所有的js文件。注意,如遇到
C:webpack-re>webpack
module.js:471
throw err;
^Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:webpack-re ode_moduleshtml-webpack-pluginlibcompiler.js:11:26)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:webpack-re ode_moduleshtml-webpack-pluginindex.js:7:21)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)问题。解决办法是,项目中安装npm install webpack -
下一步把跟目录下index.html与dist中生成的html合并。