Skip to content
This repository has been archived by the owner on May 17, 2019. It is now read-only.

Commit

Permalink
Fix assetUrl for non-browser compilations, simplify implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
rtsao committed Aug 28, 2018
1 parent aa4f46c commit 2952e4a
Show file tree
Hide file tree
Showing 19 changed files with 82 additions and 175 deletions.
6 changes: 1 addition & 5 deletions build/babel-plugins/babel-plugin-asseturl/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,7 @@ function refsHandler(t, context, refs = []) {
}
args[0].replaceWith(
t.callExpression(t.identifier('require'), [
t.stringLiteral(
`__SECRET_FILE_LOADER__?storeFile=true&storeFileTarget=node!${
args[0].node.value
}`
),
t.stringLiteral(`__SECRET_FILE_LOADER__!${args[0].node.value}`),
])
);
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { assetUrl } from 'fusion-core';
import { assetUrl as assetUrlOther } from 'assetUrl';
const path = './test';
assetUrl(require("__SECRET_FILE_LOADER__?storeFile=true&storeFileTarget=node!./path"));
assetUrl(require("__SECRET_FILE_LOADER__!./path"));
assetUrlOther(path);
assetUrl(require("__SECRET_FILE_LOADER__?storeFile=true&storeFileTarget=node!./path"));
assetUrl(require("__SECRET_FILE_LOADER__!./path"));
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assetUrl as frameworkAssetUrl } from 'fusion-core';
import assetUrl from 'assetURL';
assetUrl('./path');
frameworkAssetUrl(require("__SECRET_FILE_LOADER__?storeFile=true&storeFileTarget=node!./path"));
frameworkAssetUrl(require("__SECRET_FILE_LOADER__!./path"));
11 changes: 4 additions & 7 deletions build/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const {
} = require('../lib/compression');
const resolveFrom = require('resolve-from');

const AssetsManifestPlugin = require('./file-loader-asset-manifest-plugin');
// const AssetsManifestPlugin = require('./file-loader-asset-manifest-plugin');
const ClientSourceMapPlugin = require('./client-source-map-plugin');
const ChunkModuleManifestPlugin = require('./chunk-module-manifest-plugin');
const chunkModuleManifest = require('./chunk-module-manifest');
Expand Down Expand Up @@ -411,14 +411,12 @@ function getConfig({target, env, dir, watch, cover}) {
},
plugins: [
new ProgressBarPlugin(),
// TODO(#9): relying only on timestamp will invalidate service worker after every build
// optimize by importing all chunk names to sw and then remove timestamp in non-dev.
target === 'web' && env === 'production' && zopfliWebpackPlugin, // gzip
env === 'production' && zopfliWebpackPlugin, // gzip
// generate compressed files
target === 'web' && env === 'production' && brotliWebpackPlugin, // brotli
env === 'production' && brotliWebpackPlugin, // brotli
// target === 'web' && env === 'production' && pngquantWebpackPlugin, // png TODO(#10): production server requires libpng-dev installed to use this
// target === 'web' && env === 'production' && guetzliWebpackPlugin, // jpg TODO(#10): guetzli also depends on libpng-dev for some reason
target === 'web' && env === 'production' && svgoWebpackPlugin, // svg
env === 'production' && svgoWebpackPlugin, // svg
// In development, skip the emitting phase on errors to ensure there are
// no assets emitted that include errors. This fixes an issue with hot reloading
// server side code and recovering from errors correctly. We only want to do this
Expand Down Expand Up @@ -474,7 +472,6 @@ function getConfig({target, env, dir, watch, cover}) {
}),
// case-insensitive paths can cause problems
new CaseSensitivePathsPlugin(),
target === 'web' && new AssetsManifestPlugin(),
target === 'node' &&
new webpack.BannerPlugin({
raw: true,
Expand Down
45 changes: 0 additions & 45 deletions build/file-loader-asset-manifest-plugin.js

This file was deleted.

29 changes: 0 additions & 29 deletions build/file-loader-asset-storage.js

This file was deleted.

102 changes: 17 additions & 85 deletions build/file-loader.js
Original file line number Diff line number Diff line change
@@ -1,93 +1,25 @@
/** Copyright (c) 2018 Uber Technologies, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
/* eslint-env node */
// @flow
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
const path = require('path');
const loaderUtils = require('loader-utils');
const storageSingleton = require('./file-loader-asset-storage.js');

module.exports = function fileLoader(content /*: string */) {
if (!this.emitFile)
throw new Error('emitFile is required from module system');

const options = loaderUtils.getOptions(this) || {};

const config = {
publicPath: undefined,
useRelativePath: false,
name: '[hash].[ext]',
storeFile: false,
storeFileTarget: null,
};

// options takes precedence over config
Object.keys(options).forEach(attr => {
config[attr] = options[attr];
});
const path = require("path");
const loaderUtils = require("loader-utils");

const context =
options.context ||
this.rootContext ||
(this.options && this.options.context);
let url = loaderUtils.interpolateName(this, config.name, {
context,
content,
regExp: void 0,
module.exports = function fileLoader(content /*: string */) {
const url = loaderUtils.interpolateName(this, "[hash].[ext]", {
context: this.rootContext,
content
});

let outputPath = '';

const filePath = this.resourcePath;
if (config.useRelativePath) {
// eslint-disable-next-line no-mixed-operators
const issuerContext =
(this._module && this._module.issuer && this._module.issuer.context) ||
context;
const relativeUrl =
issuerContext &&
path
.relative(issuerContext, filePath)
.split(path.sep)
.join('/');
const relativePath = relativeUrl && `${path.dirname(relativeUrl)}/`;
// eslint-disable-next-line no-bitwise
if (~relativePath.indexOf('../')) {
// eslint-disable-line no-bitwise
outputPath = path.posix.join(outputPath, relativePath, url);
} else {
outputPath = relativePath + url;
}
url = relativePath + url;
} else {
outputPath = url;
}
// Assets should always go into client dist directory, regardless of source
const outputPath = path.posix.join("../client", url);

let publicPath = `__webpack_public_path__ + ${JSON.stringify(url)}`;
if (config.publicPath !== undefined) {
// support functions as publicPath to generate them dynamically
publicPath = JSON.stringify(
typeof config.publicPath === 'function'
? config.publicPath(url)
: config.publicPath + url
);
}
this.emitFile(outputPath, content);

const storage = storageSingleton.getStorage();
const {storeFile, storeFileTarget} = config;
if (options.emitFile === undefined || options.emitFile) {
// when storeFile param is passed we don't emit a file
// but store it to be added added later as an additional asset to a compilation
// it allows adding these files in a different compilation
if (storeFile && (!storeFileTarget || this.target === storeFileTarget)) {
storage.addFile(outputPath, content);
} else {
this.emitFile(outputPath, content);
}
}

return `module.exports = ${publicPath};`;
return `module.exports = __webpack_public_path__ + ${JSON.stringify(url)};`;
};

module.exports.raw = true;
18 changes: 18 additions & 0 deletions test/cli/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,24 @@ test('`fusion build` compresses assets for production', async t => {
t.end();
});

test('`fusion build` puts server assets in client directory', async t => {
const dir = path.resolve(__dirname, '../fixtures/server-assets');
await cmd(`build --dir=${dir} --production`);

const fusion_folder = '.fusion/dist/production/client/';
fs.readdir(path.resolve(dir, fusion_folder), (err, files) => {
t.ok(
files.includes('54dcbe888c1b1145462ae09d6610ab82.txt'),
'has server asset'
);
t.ok(
files.includes('2642b2c23331388417654062a7058f82.txt'),
'has universal asset'
);
});
t.end();
});

test('`fusion build` with dynamic imports', async t => {
const dir = path.resolve(__dirname, '../fixtures/dynamic-import');
await cmd(`build --dir=${dir}`);
Expand Down
9 changes: 9 additions & 0 deletions test/cli/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ test('`fusion dev` works with assets', async t => {
fs.readFileSync(path.resolve(dir, 'src/static/test.css')).toString(),
'serves css file from memory correctly'
);
t.equal(
await request(
`http://localhost:${port}/_static/b78cb0eaf8604dad0108350cb5149457.txt`
),
fs
.readFileSync(path.resolve(dir, 'src/static/test-server-asset.txt'))
.toString(),
'serves server asset from memory correctly'
);
t.equal(await request(`http://localhost:${port}/dirname`), 'src');
t.equal(await request(`http://localhost:${port}/filename`), 'src/main.js');
t.equal(
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/assets/.fusionrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
assumeNoImportSideEffects: true
};
4 changes: 4 additions & 0 deletions test/fixtures/assets/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ if (typeof window !== 'undefined') {
window.__hoistedUrl__ = hoistedUrl;
}

import {serverAsset} from "./server-asset.js";

export default (async function() {
const app = new App('element', el => el);
__NODE__ &&
Expand All @@ -26,6 +28,8 @@ export default (async function() {
ctx.body = assetUrl('./static/test.json');
} else if (ctx.url === '/json-import') {
ctx.body = JSON.stringify(jsonData);
} else if (ctx.url === '/server-asset') {
ctx.body = assetUrl("./static/test-server-asset.txt");
}
return next();
});
Expand Down
Empty file.
1 change: 1 addition & 0 deletions test/fixtures/assets/src/static/test-server-asset.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
test server assets
1 change: 0 additions & 1 deletion test/fixtures/compress-assets/src/main.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import App from 'fusion-core';
import {assetUrl} from 'fusion-core';


export default async function() {
const app = new App('element', el => el);
assetUrl('./assets/SVG_logo.svg');
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/server-assets/.fusionrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
assumeNoImportSideEffects: true
};
1 change: 1 addition & 0 deletions test/fixtures/server-assets/src/assets/server-asset.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
server asset
1 change: 1 addition & 0 deletions test/fixtures/server-assets/src/assets/universal-asset.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
universal asset
14 changes: 14 additions & 0 deletions test/fixtures/server-assets/src/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import App, {assetUrl} from 'fusion-core';

import {serverAsset} from "./server-assets.js";

const asset = assetUrl('./assets/universal-asset.txt');

export default async function() {
const app = new App('element', el => el);
if (__NODE__) {
serverAsset();
}
console.log(asset);
return app;
}
3 changes: 3 additions & 0 deletions test/fixtures/server-assets/src/server-assets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import {assetUrl} from 'fusion-core';

export const serverAsset = () => assetUrl('./assets/server-asset.txt');

0 comments on commit 2952e4a

Please sign in to comment.