diff --git a/lib/gen-id.js b/lib/gen-id.js index 1e3bd10..ce9f887 100644 --- a/lib/gen-id.js +++ b/lib/gen-id.js @@ -1,6 +1,12 @@ -const idRegistory = Object.create(null) -let uid = 0 +// borrowed from vue-loader +const path = require('path') +const hash = require('hash-sum') +const cache = Object.create(null) +const sepRE = new RegExp(path.sep.replace('\\', '\\\\'), 'g') -module.exports = filePath => { - return idRegistory[filePath] || (idRegistory[filePath] = ++uid) +module.exports = function genId (file, context) { + const contextPath = context.split(path.sep) + const rootId = contextPath[contextPath.length - 1] + file = rootId + '/' + path.relative(context, file).replace(sepRE, '/') + return cache[file] || (cache[file] = hash(file)) } diff --git a/lib/index.js b/lib/index.js index a52f2d9..865b5ff 100644 --- a/lib/index.js +++ b/lib/index.js @@ -7,7 +7,7 @@ const sourceMap = require('source-map') const SourceMapConsumer = sourceMap.SourceMapConsumer module.exports = function(contents, sourcemap) { - const id = genId(this.resourcePath) + const id = genId(this.resourcePath, process.cwd()) let hasComponent = false const parseOptions = { sourceType: 'module' } diff --git a/test/specs/index.spec.js b/test/specs/index.spec.js index 71e0e17..cbe6b80 100644 --- a/test/specs/index.spec.js +++ b/test/specs/index.spec.js @@ -1,9 +1,19 @@ const path = require('path') const fs = require('fs') -const DefaultLoader = require('../../lib/index') +const loader = require('../../lib/index') -class Loader extends DefaultLoader { - callback(err, contents, sourcemap) { this.callbackAnswer = { err, contents, sourcemap } } +function loadCode(data) { + let callbackAnswer + + loader.call({ + resourcePath: '/path/to/test.html', + options: {}, + callback: (err, contents, sourcemap) => { + callbackAnswer = { err, contents, sourcemap } + } + }, data) + + return callbackAnswer } function test (name) { @@ -11,8 +21,8 @@ function test (name) { const expected = fs.readFileSync(path.resolve(__dirname, '../expects', name), 'utf8') it(name, () => { - const loader = new Loader(src) - expect(loader.callbackAnswer.contents.replace(/if \(module\.hot\)[\s\S]*$/, '').trim()).toBe(expected.trim()) + const callbackAnswer = loadCode(src) + expect(callbackAnswer.contents.replace(/if \(module\.hot\)[\s\S]*$/, '').trim()).toBe(expected.trim()) }) }