非JS文件
打包非JS文件,这里用CSS文件为例。
结构&目录
新建style.css文件
body{
background-color: green;
}修改入口文件 entry.js 引入文件style.css
document.write('I am entry.js');
document.write('<br/>');
document.write(require('./module'));
// CSS文件
require('./style.css');报错
直接输入命令
$ webpack entry.js -o bundle.js --mode=development会进行报错
ERROR in ./style.css 1:4
Module parse failed: Unexpected token (1:4)
You may need an appropriate loader to handle this file type.
> body{
| background-color: green;
| }
@ ./entry.js 7:0-22这是webpack识别不来报错,webpack默认是无法打包非JS的文件,需要安装loader的包。
loader
先通过命令
$ npm init -y进行生成 package.json
rote to /Users/amor/Desktop/webpack/package.json:
{
"name": "webpack",
"version": "1.0.0",
"description": "",
"main": "bundle.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Azr",
"license": "ISC"
}安装loader
$ npm i style-loader css-loader -D页面增加loader
更改入口文件entry.js,将CSS文件的引入进行更改
document.write('I am entry.js');
document.write('<br/>');
document.write(require('./module'));
// CSS文件
require("!style-loader!css-loader!./style.css") 重新编译打包,刷新页面,就可以看到green的页面背景。
命令行增加loader
将 入口文件entry.js 中的
require("!style-loader!css-loader!./style.css") 修改为
require("./style.css") 然后执行:
$ webpack entry.js -o bundle.js --mode=development --module-bind 'css=style-loader!css-loader'
有时候大概需要使用双引号
$ webpack entry.js -o bundle.js --mode=development --module-bind "css=style-loader!css-loader"
报错
event not found: css的时候,更改一下引号的类型。
2. 以下报错,是将命令行输入错误导致的。一定是
--module-bind "css=style-loader!css-loader"style-loader在前面的。报错内容:
ERROR in ./style.css Module build failed (from ./node_modules/css-loader/index.js): Unknown word (2:1) 2 | var content = require("!!./node_modules/style-loader/index.js!./node_modules/css-loader/index.js!./style.css"); | ^ 3 | 4 | if(typeof content === 'string') content = [[module.id, content, '']]; 5 |
可以自己进行更改样式,来进行测试。
Last updated