案例: webpack自定义loader解析.chenjiang
后缀名的文件
整体目录:
- chenjiangLoader.js文件代码
// 正则匹配script标签中的内容
const REG = /<script>([\s\S]*)<\/script>/;module.exports = function (source) {const __source = source.match(REG);return __source && __source[1] ? __source[1] : source;
};
- test.chenjiang文件代码
<script>export default {name: 'chenjiang',age: 24}
</script>
- 配置webpack的loader
const path = require("path");module.exports = {entry: "./src/index.js",output: {path: path.resolve(__dirname, "dist"),filename: "bundle.js",},mode: "development",module: {rules: [{test: /\.chenjiang$/,use: [path.resolve(__dirname, "loader/chenjiangLoader.js")],},],},
};
- 主入口文件代码
import Utils from "./test.chenjiang";console.log("自定义文件后缀名:", Utils.name);
- 运行命令
前提要npm install webpack webpack-cli -D
npx webpack
- 访问index.html文件
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script type="application/javascript" src="../dist/bundle.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>