I'm experimenting with building a site that leverages native browser support for ES6 JavaScript modules (not requiring build tools). Something I noticed early on is that unlike webpack the browser was not happy with a statement like import "/myapp/style.css;"
.
我正在尝试构建一个利用本地浏览器对ES6 JavaScript模块的支持(不需要构建工具)的站点。我早先注意到的一件事是,与webpack不同的是,浏览器对像IMPORT“/myapp/style.css;”这样的语句并不满意。
Being able to associate CSS files with JavaScript-based components is really nice from a dependency tree maintenance perspective.
从依赖关系树维护的角度来看,能够将CSS文件与基于JavaScript的组件相关联真的很棒。
I'm wondering if there is a recommended approach to achieving this. Some ideas I've considered:
我想知道是否有一种推荐的方法来实现这一点。我考虑过的一些想法如下:
- Using something like JSS to move CSS into JS. Somewhat unappealing because you lose the IDE css syntax support and I assume that without a build process this is slower.
- Keeping CSS separate and using import statements within CSS to mirror JS dependencies. Unappealing to declare dependencies twice, and I don't think the browser will dedupe CSS imports like it does for modules.
- Establish a convention that Foo.js "auto-imports" Foo.css if available; write server-side logic that traverses the dependency tree and emits the relevant link tags. Seems like it will work, but requires more custom infrastructure (essentially what a build tool would do, but at runtime).
Is there a better way?
有没有更好的办法?
更多回答
You're overthinking this. Use something like Vite as a scaffolding/build tool and it will take care of this for you. Just make sure any CSS modules are written [name].module.css
.
你想得太多了。使用像VTE这样的东西作为脚手架/构建工具,它将为您解决这一问题。只要确保所有的css模块都写成[name].mode.css即可。
^ @Andy: Maybe OP can provide clarity, but I interpret "a site that leverages native browser support for ES6 JavaScript modules" to mean "this project doesn't use build tools — I'm shipping raw source code".
^@Andy:也许OP可以提供清晰度,但我将“一个利用本地浏览器对ES6 JavaScript模块的支持的站点”解释为“这个项目不使用构建工具--我提供的是原始源代码”。
@jsejcksn probably. Part of the problem is that CSS modules are not part of any standard (like ES modules) so implementation has to be done through a tool. You either define the tooling yourself, or use something like Vite which deals with CSS modules out of the box.
@jsejcksn可能。部分问题是,CSS模块不是任何标准(如ES模块)的一部分,因此实现必须通过工具来完成。您可以自己定义工具,也可以使用诸如vite之类的工具来处理开箱即用的css模块。
At the current time, there is no JavaScript runtime which implements a “CSS modules” API, so you’ll need to implement such a system yourself. Detailing such an implementation is far too complex to be on topic for a single Stack Overlow Q/A, but you can start by learning about the CSSOM APIs, generating deterministic hash strings, deduplication strategies, and researching existing tools’ “CSS modules” compiler implementations (e.g. esbuild, webpack, etc.).
目前,还没有实现“CSS模块”API的JavaScript运行时,因此您需要自己实现这样一个系统。详细描述这样的实现太复杂了,不能作为单个Stack Overlow Q/A的主题,但您可以从学习CSSOMAPI、生成确定性散列字符串、重复数据删除策略开始,并研究现有工具的“css模块”编译器实现(例如EsBuild、webpack等)。
我是一名优秀的程序员,十分优秀!