Coo*_*lue 4 rollup d3.js es6-modules
我知道 import 语句提供了对模块的只读绑定,我猜它取决于模块加载器,但是它是否可以使用 ES6 模块导入、装饰和重新导出?
例如,使用 rollup.js 时会失败
测试插件.js
import * as d3 from 'd3'
d3.ui = {test: 1};
export default d3;
Run Code Online (Sandbox Code Playgroud)
索引.js
import * as d3 from 'd3'
import './src/test.plugin'
Run Code Online (Sandbox Code Playgroud)
汇总错误...
Illegal reassignment to import 'd3'
src\test.plugin.js (6:0)
4:
5: import * as d3 from 'd3'
6: d3.ui = {test: 1};
Run Code Online (Sandbox Code Playgroud)
这也是如此...
test.plugin.js
export default (d3) => d3.ui = {test: 1};
Run Code Online (Sandbox Code Playgroud)
索引.js
import * as d3 from 'd3'
import test from './src/test.plugin'
test(d3);
Run Code Online (Sandbox Code Playgroud)
第一个失败是因为导入是不可变的,第二个失败是因为模块解析是静态的。
ES6 模块是否可以使用装饰器模式?
问题是模块对象不可扩展。可扩展的是模块对象内的对象。
模块A
let mod = { a, b, c };
// Once exported the "mod" object cannot be extended from the outside
export mod;
Run Code Online (Sandbox Code Playgroud)
索引.js
// What you are saying here is
import * as mod from "moduleA.js"
// mod cannot be extended here
// mod.b can be extended though
mod.b.ui = {test: 1};
Run Code Online (Sandbox Code Playgroud)
当您执行默认导出时,您可以将其扩展为default有效的嵌套属性。
模块A
let mod = { a, b, c };
// Once exported as default
export default mod;
Run Code Online (Sandbox Code Playgroud)
索引.js
import mod from "moduleA.js"
// mod is effectively a prop of the module object, so it can be extended
mod.d = { ... };
Run Code Online (Sandbox Code Playgroud)
对于您的情况,您可以执行以下操作:
测试插件.js
// Import d3 as a composition of props
import * as d3 from 'd3';
// Create a new object using the Object.assign operator
// You can use the spread operator too
const d3plus = Object.assign({ui: () => 'test'}, d3);
// Now d3plus will be extendable!
export default d3plus;
Run Code Online (Sandbox Code Playgroud)
索引.js
import d3plus from 'test.plugin.js';
console.log(d3plus.ui);
Run Code Online (Sandbox Code Playgroud)
这是我在阅读规范时错误地回答的。公平地说,其他一些模块捆绑器之前也犯了错误,因为 es6模块非常 困难。
当你有模块A并且想用新功能/东西装饰它时,你有两种选择:
A,然后仅在稍后使用包装器在前一种情况下你可以这样做:
测试插件.js
import * as d3 from 'd3'
d3.ui = {test: 1};
export default d3;
Run Code Online (Sandbox Code Playgroud)
索引.js
// Note that using this wrapper makes sure you have the extra stuff all the time
import d3plus from './src/test.plugin';
console.log(d3plus.ui);
Run Code Online (Sandbox Code Playgroud)
使用第二种方法,您必须获得装饰器操作的结果:
测试插件.js
export default (d3) => {
d3.ui = {test: 1};
// Do not forget to return the new object
return d3;
};
Run Code Online (Sandbox Code Playgroud)
索引.js
import * as d3 from 'd3'
import pluginify from './src/test.plugin'
// Note that this change is local to this module only
const d3plus = pluginify(d3);
console.log(d3plus.ui);
Run Code Online (Sandbox Code Playgroud)
您可以使用更多技巧来实现相同的结果,但我建议明确您应用于模块的丰富过程。