Giter VIP home page Giter VIP logo

web-node-engineer's Introduction

前端工程化学习

解决node中使用esm问题

ESM不再提供Node某些特性与不能灵活引用json文件了,因此__dirname__filenamerequiremoduleexports这几个特性将无法使用。

不过我们可以自动打上补丁,来解决这些问题:

  • __filename__dirname可用import.meta对象重建
  • requiremoduleexports可用importexport代替
  • json文件的引用可用Fs模块readFileSyncJSON.parse()代替
import { readFileSync } from "fs";
import { dirname } from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
console.log(__filename, __dirname);

const json = readFileSync("./info.json");
const info = JSON.parse(json);

使用babel转义高级es语法

  • @babel/cli:提供支持@babel/core的命令运行环境
  • @babel/core:提供转译函数
  • @babel/node:提供支持ESM的命令运行环境
  • @babel/preset-env:提供预设语法转换集成环境
{
    "script":{
        "start":"babel-node src/index.js"
    },
    	"babel": {
		"presets": [
			"@babel/preset-env"
		]
	}
}

安装nodemon监控文件变化

pnpm i nodemon -D

package.json中指定nodemonConfig相关配置,将start命令替换为nodemon -x babel-node src/index.js

{
	"nodemonConfig": {
		"env": {
			"NODE_ENV": "dev"
		},
		"execMap": {
			"js": "node --harmony"
		},
		"ext": "js json",
		"ignore": [
			"dist/"
		],
		"watch": [
			"src/"
		]
	}
}

web-node-engineer's People

Watchers

maojun avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.