一、加载 json 文件
内置支持 JSON 解析,也就是说 import Data from './data.json'
默认将正常运行。
1.1 添加 json 文件
demo09
|- package.json
|- webpack.config.js
|- /dist
|- bundle.js
|- index.html
|- /src
|- 华文彩云.ttf
|- icon.png
|- style.css
|- index.js
+ |- /data
+ |- json.json
|- /node_modules
1.2 编辑 index.js 文件
import "./style.css"
import Icon from './icon.jpg';
import jsonData from "./data/json.json"
//生成一个内容为Hello webpack !的div标签
function component() {
let element = document.createElement('div');
element.innerHTML = "Hello webpack !";
//添加class
element.classList.add("hello");
return element;
}
//将生成的div标签添加到body中去
document.body.appendChild(component());
function addImage() {
let element = document.createElement('img');
//设置图片路径
element.src = Icon;
//添加class
element.classList.add("image");
return element;
}
//将生成的img标签添加到body中去
document.body.appendChild(addImage());
//打印 JSON 数据
console.log("JSON",jsonData);
1.3 重新构建
npm run build
//或者
yanr build
yarn run v1.16.0
$ webpack
Hash: 60e06afbd947848d1740
Version: webpack 4.35.3
Time: 585ms
Built at: 07/18/2019 3:12:17 PM
Asset Size Chunks Chunk Names
71eaacb7c100911a2acca6547fa6520a.ttf 5.4 MiB [emitted] [big]
76e7e08e0b3a04a612c89ad13c999813.jpg 51 KiB [emitted]
bundle.js 7.8 KiB 0 [emitted] main
Entrypoint main = bundle.js
[0] ./src/icon.jpg 82 bytes {0} [built]
[1] ./src/data/json.json 70 bytes {0} [built]
[2] ./src/index.js 657 bytes {0} [built]
[3] ./src/style.css 1.06 KiB {0} [built]
[4] ./node_modules/css-loader/dist/cjs.js!./src/style.css 558 bytes {0} [built]
[7] ./src/华文彩云.ttf 82 bytes {0} [built]
+ 4 hidden modules
WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/
WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
71eaacb7c100911a2acca6547fa6520a.ttf (5.4 MiB)
WARNING in webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
For more info visit https://webpack.js.org/guides/code-splitting/
✨ Done in 1.52s.
1.4 运行 index.html 文件
在 Chrome 浏览器中打开文件,然后使用 检查 功能,查看 Console 控制台输出
JSON Object
name: "Webpack"
url: "https://webpack.docschina.org"
__proto__: Object
二、加载 xml 文件
解析 xml 文件需要 xml-loader 支持。
2.1 添加 xml 文件
demo09
|- package.json
|- webpack.config.js
|- /dist
|- bundle.js
|- index.html
|- /src
|- 华文彩云.ttf
|- icon.png
|- style.css
|- index.js
|- /data
|- json.json
+ |- xml.xml
|- /node_modules
2.2 安装 xml-loader
npm install --save-dev xml-loader
//或者
yarn add xml-loader --dev
安装成功
yarn add v1.16.0
[1/4] ? Resolving