配置loader,经过加载器处理文件,例如css sass less等,告诉webpack每一种文件都须要使用什么来加载器来处理。css
1.node.js安装好以后也会自动默认安装好npm,因此cmd cd进入当前项目下输入npm install babel-loader babel babel-core css-loader style-loader url-loader file-loader less-loader less --save-dev命令下载这些包。html
2.修改webpack.config.js文件,将加载器引入node
module.exports = { entry : './src/js/entry.js', output : { filename : 'index.js', path : __dirname + '/out' }, module : { rules: [ {test: /.js$/, use: ['babel-loader']}, {test: /.css$/, use: ['style-loader', 'css-loader']},/*解析css, 并把css添加到html的style标签里*/ //{test: /.css$/, use: ExtractTextPlugin.extract({fallback: 'style-loader',use: 'css-loader'})},/*解析css, 并把css变成文件经过link标签引入*/ {test: /.(jpg|png|gif|svg)$/, use: ['url-loader?limit=8192&name=./[name].[ext]']},/*解析图片*/ {test: /.less$/, use: ['style-loader', 'css-loader', 'less-loader']}/*解析less, 把less解析成浏览器能够识别的css语言*/ ] }, }
3.在项目文件夹下的src文件夹下的css文件下建立index.css,而且修改index.html文件webpack
//index.css .demo1 { width: 100px; height: 100px; background: red; } .demo2 { width: 200px; height: 200px; background: orange; }
//index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>text</title> </head> <body> <div class="demo1"></div> <div class="demo2"></div> <script src="./out/index.js"></script> </body> </html>
由于在webpack中全部文件都是模块, 因此必需要将css引入. 在刚刚的entry.js中添加以下代码.web
//entry.js require('../css/index.css');//引入css文件 console.log("1234");
打包webpack一下看看效果npm
4.引用多个js文件浏览器
在src文件下新建tool.js文件sass
//tool.js var tool = {//获取DOM元素 getDom: function(className) { return document.getElementsByClassName(className)[0]; } } module.exports = tool;//模块出口
src的js下建立一个demo1.js文件, demo2.js同理babel
var obj = require('./tool.js'); var demo1 = { init: function() { this.bindEvent(); }, bindEvent: function() { //var demo1 = document.getElementsByClassName('demo1')[0]; var demo1 = obj.getDom('demo1'); demo1.onclick = this.changeStyle; }, changeStyle: function() { this.style.width = '200px'; this.style.height = '200px'; this.style.background = 'green'; console.log('1'); } } module.exports = demo1;
修改入口文件entry.jsless
require('../css/index.css'); var demo1 = require('../js/demo1.js'); var demo2 = require('../js/demo2.js'); demo1.init(); demo2.init();
webpack一下, 看看效果