路径有两个反斜杠,能教我代码具体写来解决这个问题吗?我的node基础不好。
来源:6-6 Bundler 源码编写( Dependencies Graph )
慕的地3200337
2020-05-07
dependencies: { ‘./message.js’: ‘./src\message.js’ }
下面时配置代码:
const fs = require(‘fs’)
const parser = require(’@babel/parser’)
const path = require(‘path’)
const traverse = require(’@babel/traverse’).default
const babel = require(’@babel/core’)
const muduleAnalyser = (filename) => {
const content = fs.readFileSync(filename, ‘utf-8’)
const ast = parser.parse(content, {
sourceType: ‘module’
})
const dependencies = {}
traverse(ast, {
ImportDeclaration ({ node }) {
const dirname = path.dirname(filename)
const newFile = ‘./’ + path.join(dirname, node.source.value)
dependencies[node.source.value] = newFile
}
})
const { code } = babel.transformFromAst(ast, null, {
presets: [’@babel/preset-env’]
})
return {
filename,
dependencies,
code
}
}
const moduleInfo = muduleAnalyser(’./src/index.js’)
console.log(moduleInfo)
1回答
-
问题出在配置traverse的时候用的 path.join
traverse(ast, { ImportDeclaration({ node }) { const dirname = path.dirname(filename) // 下面如果是 path.join ,在 windows 系统中路径就是 ./src\message.js\ // 会出现斜杠不一样的问题,用 path.posix.join 就能解决 const newFile = './' + path.posix.join(dirname, node.source.value, '/') dependencies[node.source.value] = newFile } })
112020-05-12
相似问题