0
点赞
收藏
分享

微信扫一扫

【Git】02-Git常见应用

水墨_青花 2023-09-18 阅读 35

案例: 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);
  • 运行命令
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>
举报

相关推荐

0 条评论