klei/gulp-inject

js type="modules"

ThomasBrierley opened this issue · 3 comments

Hi @joakimbeng I've written a little transform for automatically adding type="module" for script tags when the content includes the new ES6 import/export statements.

Would you be interested in including it as the default script transform? I ask first because it's more costly in that it must do some regex on the file source instead of just using the path name.

Nevermind

XShep commented

@ThomasBrierley Hello, i know that it was long time ago, but how did you solve the problem? I have some JS files which have "import" statements. I'm trying to find any solution to inject those files with module type.

Hi @XShep I don't use this or gulp any more, but this is what I did:
https://github.com/LearningScience/gurt-frags/blob/master/lib/gurt-frags.js#L5

plugin.inject.transform.html.js = (path, file) => {
	file = file.contents.toString();
	let test = /(?:^|\n)\s*(import|export)\s+/;
	let type = test.test(file) ? 'module' : '';
	return `<script type="${type}" src="${path}"></script>`;
};

I'd recommend switching to esbuild if it's within your power. With esbuild you don't actually use native imports in the browser, you always bundle, even on serve, but it's so fast and you have sourcemaps that it works great.